dgenerate-ultralytics-headless 8.3.253__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 (299) hide show
  1. dgenerate_ultralytics_headless-8.3.253.dist-info/METADATA +405 -0
  2. dgenerate_ultralytics_headless-8.3.253.dist-info/RECORD +299 -0
  3. dgenerate_ultralytics_headless-8.3.253.dist-info/WHEEL +5 -0
  4. dgenerate_ultralytics_headless-8.3.253.dist-info/entry_points.txt +3 -0
  5. dgenerate_ultralytics_headless-8.3.253.dist-info/licenses/LICENSE +661 -0
  6. dgenerate_ultralytics_headless-8.3.253.dist-info/top_level.txt +1 -0
  7. tests/__init__.py +23 -0
  8. tests/conftest.py +59 -0
  9. tests/test_cli.py +131 -0
  10. tests/test_cuda.py +216 -0
  11. tests/test_engine.py +157 -0
  12. tests/test_exports.py +309 -0
  13. tests/test_integrations.py +151 -0
  14. tests/test_python.py +777 -0
  15. tests/test_solutions.py +371 -0
  16. ultralytics/__init__.py +48 -0
  17. ultralytics/assets/bus.jpg +0 -0
  18. ultralytics/assets/zidane.jpg +0 -0
  19. ultralytics/cfg/__init__.py +1028 -0
  20. ultralytics/cfg/datasets/Argoverse.yaml +78 -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 +32 -0
  25. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  26. ultralytics/cfg/datasets/Objects365.yaml +447 -0
  27. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  28. ultralytics/cfg/datasets/TT100K.yaml +346 -0
  29. ultralytics/cfg/datasets/VOC.yaml +102 -0
  30. ultralytics/cfg/datasets/VisDrone.yaml +87 -0
  31. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  32. ultralytics/cfg/datasets/brain-tumor.yaml +22 -0
  33. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  34. ultralytics/cfg/datasets/coco-pose.yaml +64 -0
  35. ultralytics/cfg/datasets/coco.yaml +118 -0
  36. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  37. ultralytics/cfg/datasets/coco128.yaml +101 -0
  38. ultralytics/cfg/datasets/coco8-grayscale.yaml +103 -0
  39. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  40. ultralytics/cfg/datasets/coco8-pose.yaml +47 -0
  41. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  42. ultralytics/cfg/datasets/coco8.yaml +101 -0
  43. ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
  44. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  45. ultralytics/cfg/datasets/dog-pose.yaml +52 -0
  46. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  47. ultralytics/cfg/datasets/dota8.yaml +35 -0
  48. ultralytics/cfg/datasets/hand-keypoints.yaml +50 -0
  49. ultralytics/cfg/datasets/kitti.yaml +27 -0
  50. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  51. ultralytics/cfg/datasets/medical-pills.yaml +21 -0
  52. ultralytics/cfg/datasets/open-images-v7.yaml +663 -0
  53. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  54. ultralytics/cfg/datasets/signature.yaml +21 -0
  55. ultralytics/cfg/datasets/tiger-pose.yaml +41 -0
  56. ultralytics/cfg/datasets/xView.yaml +155 -0
  57. ultralytics/cfg/default.yaml +130 -0
  58. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  59. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  60. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  61. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  62. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  63. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  64. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  65. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  66. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  67. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  68. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  69. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  70. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  71. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  72. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  73. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  74. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  75. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  76. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  77. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  78. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  79. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  80. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  81. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  82. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  83. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  84. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  85. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  86. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  87. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +48 -0
  88. ultralytics/cfg/models/v8/yoloe-v8.yaml +48 -0
  89. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  90. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  91. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  92. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  93. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  94. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  95. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  96. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  97. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  98. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  99. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  100. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  101. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  102. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  103. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  104. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  105. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  106. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  107. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  108. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  109. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  110. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  111. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  112. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  113. ultralytics/cfg/trackers/botsort.yaml +21 -0
  114. ultralytics/cfg/trackers/bytetrack.yaml +12 -0
  115. ultralytics/data/__init__.py +26 -0
  116. ultralytics/data/annotator.py +66 -0
  117. ultralytics/data/augment.py +2801 -0
  118. ultralytics/data/base.py +435 -0
  119. ultralytics/data/build.py +437 -0
  120. ultralytics/data/converter.py +855 -0
  121. ultralytics/data/dataset.py +834 -0
  122. ultralytics/data/loaders.py +704 -0
  123. ultralytics/data/scripts/download_weights.sh +18 -0
  124. ultralytics/data/scripts/get_coco.sh +61 -0
  125. ultralytics/data/scripts/get_coco128.sh +18 -0
  126. ultralytics/data/scripts/get_imagenet.sh +52 -0
  127. ultralytics/data/split.py +138 -0
  128. ultralytics/data/split_dota.py +344 -0
  129. ultralytics/data/utils.py +798 -0
  130. ultralytics/engine/__init__.py +1 -0
  131. ultralytics/engine/exporter.py +1580 -0
  132. ultralytics/engine/model.py +1125 -0
  133. ultralytics/engine/predictor.py +508 -0
  134. ultralytics/engine/results.py +1522 -0
  135. ultralytics/engine/trainer.py +977 -0
  136. ultralytics/engine/tuner.py +449 -0
  137. ultralytics/engine/validator.py +387 -0
  138. ultralytics/hub/__init__.py +166 -0
  139. ultralytics/hub/auth.py +151 -0
  140. ultralytics/hub/google/__init__.py +174 -0
  141. ultralytics/hub/session.py +422 -0
  142. ultralytics/hub/utils.py +162 -0
  143. ultralytics/models/__init__.py +9 -0
  144. ultralytics/models/fastsam/__init__.py +7 -0
  145. ultralytics/models/fastsam/model.py +79 -0
  146. ultralytics/models/fastsam/predict.py +169 -0
  147. ultralytics/models/fastsam/utils.py +23 -0
  148. ultralytics/models/fastsam/val.py +38 -0
  149. ultralytics/models/nas/__init__.py +7 -0
  150. ultralytics/models/nas/model.py +98 -0
  151. ultralytics/models/nas/predict.py +56 -0
  152. ultralytics/models/nas/val.py +38 -0
  153. ultralytics/models/rtdetr/__init__.py +7 -0
  154. ultralytics/models/rtdetr/model.py +63 -0
  155. ultralytics/models/rtdetr/predict.py +88 -0
  156. ultralytics/models/rtdetr/train.py +89 -0
  157. ultralytics/models/rtdetr/val.py +216 -0
  158. ultralytics/models/sam/__init__.py +25 -0
  159. ultralytics/models/sam/amg.py +275 -0
  160. ultralytics/models/sam/build.py +365 -0
  161. ultralytics/models/sam/build_sam3.py +377 -0
  162. ultralytics/models/sam/model.py +169 -0
  163. ultralytics/models/sam/modules/__init__.py +1 -0
  164. ultralytics/models/sam/modules/blocks.py +1067 -0
  165. ultralytics/models/sam/modules/decoders.py +495 -0
  166. ultralytics/models/sam/modules/encoders.py +794 -0
  167. ultralytics/models/sam/modules/memory_attention.py +298 -0
  168. ultralytics/models/sam/modules/sam.py +1160 -0
  169. ultralytics/models/sam/modules/tiny_encoder.py +979 -0
  170. ultralytics/models/sam/modules/transformer.py +344 -0
  171. ultralytics/models/sam/modules/utils.py +512 -0
  172. ultralytics/models/sam/predict.py +3940 -0
  173. ultralytics/models/sam/sam3/__init__.py +3 -0
  174. ultralytics/models/sam/sam3/decoder.py +546 -0
  175. ultralytics/models/sam/sam3/encoder.py +529 -0
  176. ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
  177. ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
  178. ultralytics/models/sam/sam3/model_misc.py +199 -0
  179. ultralytics/models/sam/sam3/necks.py +129 -0
  180. ultralytics/models/sam/sam3/sam3_image.py +339 -0
  181. ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
  182. ultralytics/models/sam/sam3/vitdet.py +547 -0
  183. ultralytics/models/sam/sam3/vl_combiner.py +160 -0
  184. ultralytics/models/utils/__init__.py +1 -0
  185. ultralytics/models/utils/loss.py +466 -0
  186. ultralytics/models/utils/ops.py +315 -0
  187. ultralytics/models/yolo/__init__.py +7 -0
  188. ultralytics/models/yolo/classify/__init__.py +7 -0
  189. ultralytics/models/yolo/classify/predict.py +90 -0
  190. ultralytics/models/yolo/classify/train.py +202 -0
  191. ultralytics/models/yolo/classify/val.py +216 -0
  192. ultralytics/models/yolo/detect/__init__.py +7 -0
  193. ultralytics/models/yolo/detect/predict.py +122 -0
  194. ultralytics/models/yolo/detect/train.py +227 -0
  195. ultralytics/models/yolo/detect/val.py +507 -0
  196. ultralytics/models/yolo/model.py +430 -0
  197. ultralytics/models/yolo/obb/__init__.py +7 -0
  198. ultralytics/models/yolo/obb/predict.py +56 -0
  199. ultralytics/models/yolo/obb/train.py +79 -0
  200. ultralytics/models/yolo/obb/val.py +302 -0
  201. ultralytics/models/yolo/pose/__init__.py +7 -0
  202. ultralytics/models/yolo/pose/predict.py +65 -0
  203. ultralytics/models/yolo/pose/train.py +110 -0
  204. ultralytics/models/yolo/pose/val.py +248 -0
  205. ultralytics/models/yolo/segment/__init__.py +7 -0
  206. ultralytics/models/yolo/segment/predict.py +109 -0
  207. ultralytics/models/yolo/segment/train.py +69 -0
  208. ultralytics/models/yolo/segment/val.py +307 -0
  209. ultralytics/models/yolo/world/__init__.py +5 -0
  210. ultralytics/models/yolo/world/train.py +173 -0
  211. ultralytics/models/yolo/world/train_world.py +178 -0
  212. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  213. ultralytics/models/yolo/yoloe/predict.py +162 -0
  214. ultralytics/models/yolo/yoloe/train.py +287 -0
  215. ultralytics/models/yolo/yoloe/train_seg.py +122 -0
  216. ultralytics/models/yolo/yoloe/val.py +206 -0
  217. ultralytics/nn/__init__.py +27 -0
  218. ultralytics/nn/autobackend.py +964 -0
  219. ultralytics/nn/modules/__init__.py +182 -0
  220. ultralytics/nn/modules/activation.py +54 -0
  221. ultralytics/nn/modules/block.py +1947 -0
  222. ultralytics/nn/modules/conv.py +669 -0
  223. ultralytics/nn/modules/head.py +1183 -0
  224. ultralytics/nn/modules/transformer.py +793 -0
  225. ultralytics/nn/modules/utils.py +159 -0
  226. ultralytics/nn/tasks.py +1768 -0
  227. ultralytics/nn/text_model.py +356 -0
  228. ultralytics/py.typed +1 -0
  229. ultralytics/solutions/__init__.py +41 -0
  230. ultralytics/solutions/ai_gym.py +108 -0
  231. ultralytics/solutions/analytics.py +264 -0
  232. ultralytics/solutions/config.py +107 -0
  233. ultralytics/solutions/distance_calculation.py +123 -0
  234. ultralytics/solutions/heatmap.py +125 -0
  235. ultralytics/solutions/instance_segmentation.py +86 -0
  236. ultralytics/solutions/object_blurrer.py +89 -0
  237. ultralytics/solutions/object_counter.py +190 -0
  238. ultralytics/solutions/object_cropper.py +87 -0
  239. ultralytics/solutions/parking_management.py +280 -0
  240. ultralytics/solutions/queue_management.py +93 -0
  241. ultralytics/solutions/region_counter.py +133 -0
  242. ultralytics/solutions/security_alarm.py +151 -0
  243. ultralytics/solutions/similarity_search.py +219 -0
  244. ultralytics/solutions/solutions.py +828 -0
  245. ultralytics/solutions/speed_estimation.py +114 -0
  246. ultralytics/solutions/streamlit_inference.py +260 -0
  247. ultralytics/solutions/templates/similarity-search.html +156 -0
  248. ultralytics/solutions/trackzone.py +88 -0
  249. ultralytics/solutions/vision_eye.py +67 -0
  250. ultralytics/trackers/__init__.py +7 -0
  251. ultralytics/trackers/basetrack.py +115 -0
  252. ultralytics/trackers/bot_sort.py +257 -0
  253. ultralytics/trackers/byte_tracker.py +469 -0
  254. ultralytics/trackers/track.py +116 -0
  255. ultralytics/trackers/utils/__init__.py +1 -0
  256. ultralytics/trackers/utils/gmc.py +339 -0
  257. ultralytics/trackers/utils/kalman_filter.py +482 -0
  258. ultralytics/trackers/utils/matching.py +154 -0
  259. ultralytics/utils/__init__.py +1450 -0
  260. ultralytics/utils/autobatch.py +118 -0
  261. ultralytics/utils/autodevice.py +205 -0
  262. ultralytics/utils/benchmarks.py +728 -0
  263. ultralytics/utils/callbacks/__init__.py +5 -0
  264. ultralytics/utils/callbacks/base.py +233 -0
  265. ultralytics/utils/callbacks/clearml.py +146 -0
  266. ultralytics/utils/callbacks/comet.py +625 -0
  267. ultralytics/utils/callbacks/dvc.py +197 -0
  268. ultralytics/utils/callbacks/hub.py +110 -0
  269. ultralytics/utils/callbacks/mlflow.py +134 -0
  270. ultralytics/utils/callbacks/neptune.py +126 -0
  271. ultralytics/utils/callbacks/platform.py +453 -0
  272. ultralytics/utils/callbacks/raytune.py +42 -0
  273. ultralytics/utils/callbacks/tensorboard.py +123 -0
  274. ultralytics/utils/callbacks/wb.py +188 -0
  275. ultralytics/utils/checks.py +1020 -0
  276. ultralytics/utils/cpu.py +85 -0
  277. ultralytics/utils/dist.py +123 -0
  278. ultralytics/utils/downloads.py +529 -0
  279. ultralytics/utils/errors.py +35 -0
  280. ultralytics/utils/events.py +113 -0
  281. ultralytics/utils/export/__init__.py +7 -0
  282. ultralytics/utils/export/engine.py +237 -0
  283. ultralytics/utils/export/imx.py +325 -0
  284. ultralytics/utils/export/tensorflow.py +231 -0
  285. ultralytics/utils/files.py +219 -0
  286. ultralytics/utils/git.py +137 -0
  287. ultralytics/utils/instance.py +484 -0
  288. ultralytics/utils/logger.py +506 -0
  289. ultralytics/utils/loss.py +849 -0
  290. ultralytics/utils/metrics.py +1563 -0
  291. ultralytics/utils/nms.py +337 -0
  292. ultralytics/utils/ops.py +664 -0
  293. ultralytics/utils/patches.py +201 -0
  294. ultralytics/utils/plotting.py +1047 -0
  295. ultralytics/utils/tal.py +404 -0
  296. ultralytics/utils/torch_utils.py +984 -0
  297. ultralytics/utils/tqdm.py +443 -0
  298. ultralytics/utils/triton.py +112 -0
  299. ultralytics/utils/tuner.py +168 -0
@@ -0,0 +1,529 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import shutil
7
+ import subprocess
8
+ from itertools import repeat
9
+ from multiprocessing.pool import ThreadPool
10
+ from pathlib import Path
11
+ from urllib import parse, request
12
+
13
+ from ultralytics.utils import ASSETS_URL, 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
+ + [
36
+ "mobile_sam.pt",
37
+ "mobileclip_blt.ts",
38
+ "yolo11n-grayscale.pt",
39
+ "calibration_image_sample_data_20x128x128x3_float32.npy.zip",
40
+ ]
41
+ )
42
+ GITHUB_ASSETS_STEMS = frozenset(k.rpartition(".")[0] for k in GITHUB_ASSETS_NAMES)
43
+
44
+
45
+ def is_url(url: str | Path, check: bool = False) -> bool:
46
+ """Validate if the given string is a URL and optionally check if the URL exists online.
47
+
48
+ Args:
49
+ url (str): The string to be validated as a URL.
50
+ check (bool, optional): If True, performs an additional check to see if the URL exists online.
51
+
52
+ Returns:
53
+ (bool): True for a valid URL. If 'check' is True, also returns True if the URL exists online.
54
+
55
+ Examples:
56
+ >>> valid = is_url("https://www.example.com")
57
+ >>> valid_and_exists = is_url("https://www.example.com", check=True)
58
+ """
59
+ try:
60
+ url = str(url)
61
+ result = parse.urlparse(url)
62
+ if not (result.scheme and result.netloc):
63
+ return False
64
+ if check:
65
+ r = request.urlopen(request.Request(url, method="HEAD"), timeout=3)
66
+ return 200 <= r.getcode() < 400
67
+ return True
68
+ except Exception:
69
+ return False
70
+
71
+
72
+ def delete_dsstore(path: str | Path, files_to_delete: tuple[str, ...] = (".DS_Store", "__MACOSX")) -> None:
73
+ """Delete all specified system files in a directory.
74
+
75
+ Args:
76
+ path (str | Path): The directory path where the files should be deleted.
77
+ files_to_delete (tuple): The files to be deleted.
78
+
79
+ Examples:
80
+ >>> from ultralytics.utils.downloads import delete_dsstore
81
+ >>> delete_dsstore("path/to/dir")
82
+
83
+ Notes:
84
+ ".DS_Store" files are created by the Apple operating system and contain metadata about folders and files. They
85
+ are hidden system files and can cause issues when transferring files between different operating systems.
86
+ """
87
+ for file in files_to_delete:
88
+ matches = list(Path(path).rglob(file))
89
+ LOGGER.info(f"Deleting {file} files: {matches}")
90
+ for f in matches:
91
+ f.unlink()
92
+
93
+
94
+ def zip_directory(
95
+ directory: str | Path,
96
+ compress: bool = True,
97
+ exclude: tuple[str, ...] = (".DS_Store", "__MACOSX"),
98
+ progress: bool = True,
99
+ ) -> Path:
100
+ """Zip the contents of a directory, excluding specified files.
101
+
102
+ The resulting zip file is named after the directory and placed alongside it.
103
+
104
+ Args:
105
+ directory (str | Path): The path to the directory to be zipped.
106
+ compress (bool): Whether to compress the files while zipping.
107
+ exclude (tuple, optional): A tuple of filename strings to be excluded.
108
+ progress (bool, optional): Whether to display a progress bar.
109
+
110
+ Returns:
111
+ (Path): The path to the resulting zip file.
112
+
113
+ Examples:
114
+ >>> from ultralytics.utils.downloads import zip_directory
115
+ >>> file = zip_directory("path/to/dir")
116
+ """
117
+ from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile
118
+
119
+ delete_dsstore(directory)
120
+ directory = Path(directory)
121
+ if not directory.is_dir():
122
+ raise FileNotFoundError(f"Directory '{directory}' does not exist.")
123
+
124
+ # Zip with progress bar
125
+ files = [f for f in directory.rglob("*") if f.is_file() and all(x not in f.name for x in exclude)] # files to zip
126
+ zip_file = directory.with_suffix(".zip")
127
+ compression = ZIP_DEFLATED if compress else ZIP_STORED
128
+ with ZipFile(zip_file, "w", compression) as f:
129
+ for file in TQDM(files, desc=f"Zipping {directory} to {zip_file}...", unit="files", disable=not progress):
130
+ f.write(file, file.relative_to(directory))
131
+
132
+ return zip_file # return path to zip file
133
+
134
+
135
+ def unzip_file(
136
+ file: str | Path,
137
+ path: str | Path | None = None,
138
+ exclude: tuple[str, ...] = (".DS_Store", "__MACOSX"),
139
+ exist_ok: bool = False,
140
+ progress: bool = True,
141
+ ) -> Path:
142
+ """Unzip a *.zip file to the specified path, excluding specified files.
143
+
144
+ If the zipfile does not contain a single top-level directory, the function will create a new directory with the same
145
+ name as the zipfile (without the extension) to extract its contents. If a path is not provided, the function will
146
+ use the parent directory of the zipfile as the default path.
147
+
148
+ Args:
149
+ file (str | Path): The path to the zipfile to be extracted.
150
+ path (str | Path, optional): The path to extract the zipfile to.
151
+ exclude (tuple, optional): A tuple of filename strings to be excluded.
152
+ exist_ok (bool, optional): Whether to overwrite existing contents if they exist.
153
+ progress (bool, optional): Whether to display a progress bar.
154
+
155
+ Returns:
156
+ (Path): The path to the directory where the zipfile was extracted.
157
+
158
+ Raises:
159
+ BadZipFile: If the provided file does not exist or is not a valid zipfile.
160
+
161
+ Examples:
162
+ >>> from ultralytics.utils.downloads import unzip_file
163
+ >>> directory = unzip_file("path/to/file.zip")
164
+ """
165
+ from zipfile import BadZipFile, ZipFile, is_zipfile
166
+
167
+ if not (Path(file).exists() and is_zipfile(file)):
168
+ raise BadZipFile(f"File '{file}' does not exist or is a bad zip file.")
169
+ if path is None:
170
+ path = Path(file).parent # default path
171
+
172
+ # Unzip the file contents
173
+ with ZipFile(file) as zipObj:
174
+ files = [f for f in zipObj.namelist() if all(x not in f for x in exclude)]
175
+ top_level_dirs = {Path(f).parts[0] for f in files}
176
+
177
+ # Decide to unzip directly or unzip into a directory
178
+ unzip_as_dir = len(top_level_dirs) == 1 # (len(files) > 1 and not files[0].endswith("/"))
179
+ if unzip_as_dir:
180
+ # Zip has 1 top-level directory
181
+ extract_path = path # i.e. ../datasets
182
+ path = Path(path) / next(iter(top_level_dirs)) # i.e. extract coco8/ dir to ../datasets/
183
+ else:
184
+ # Zip has multiple files at top level
185
+ path = extract_path = Path(path) / Path(file).stem # i.e. extract multiple files to ../datasets/coco8/
186
+
187
+ # Check if destination directory already exists and contains files
188
+ if path.exists() and any(path.iterdir()) and not exist_ok:
189
+ # If it exists and is not empty, return the path without unzipping
190
+ LOGGER.warning(f"Skipping {file} unzip as destination directory {path} is not empty.")
191
+ return path
192
+
193
+ for f in TQDM(files, desc=f"Unzipping {file} to {Path(path).resolve()}...", unit="files", disable=not progress):
194
+ # Ensure the file is within the extract_path to avoid path traversal security vulnerability
195
+ if ".." in Path(f).parts:
196
+ LOGGER.warning(f"Potentially insecure file path: {f}, skipping extraction.")
197
+ continue
198
+ zipObj.extract(f, extract_path)
199
+
200
+ return path # return unzip dir
201
+
202
+
203
+ def check_disk_space(
204
+ file_bytes: int,
205
+ path: str | Path = Path.cwd(),
206
+ sf: float = 1.5,
207
+ hard: bool = True,
208
+ ) -> bool:
209
+ """Check if there is sufficient disk space to download and store a file.
210
+
211
+ Args:
212
+ file_bytes (int): The file size in bytes.
213
+ path (str | Path, optional): The path or drive to check the available free space on.
214
+ sf (float, optional): Safety factor, the multiplier for the required free space.
215
+ hard (bool, optional): Whether to throw an error or not on insufficient disk space.
216
+
217
+ Returns:
218
+ (bool): True if there is sufficient disk space, False otherwise.
219
+ """
220
+ _total, _used, free = shutil.disk_usage(path) # bytes
221
+ if file_bytes * sf < free:
222
+ return True # sufficient space
223
+
224
+ # Insufficient space
225
+ text = (
226
+ f"Insufficient free disk space {free >> 30:.3f} GB < {int(file_bytes * sf) >> 30:.3f} GB required, "
227
+ f"Please free {int(file_bytes * sf - free) >> 30:.3f} GB additional disk space and try again."
228
+ )
229
+ if hard:
230
+ raise MemoryError(text)
231
+ LOGGER.warning(text)
232
+ return False
233
+
234
+
235
+ def get_google_drive_file_info(link: str) -> tuple[str, str | None]:
236
+ """Retrieve the direct download link and filename for a shareable Google Drive file link.
237
+
238
+ Args:
239
+ link (str): The shareable link of the Google Drive file.
240
+
241
+ Returns:
242
+ url (str): Direct download URL for the Google Drive file.
243
+ filename (str | None): Original filename of the Google Drive file. If filename extraction fails, returns None.
244
+
245
+ Examples:
246
+ >>> from ultralytics.utils.downloads import get_google_drive_file_info
247
+ >>> link = "https://drive.google.com/file/d/1cqT-cJgANNrhIHCrEufUYhQ4RqiWG_lJ/view?usp=drive_link"
248
+ >>> url, filename = get_google_drive_file_info(link)
249
+ """
250
+ import requests # scoped as slow import
251
+
252
+ file_id = link.split("/d/")[1].split("/view", 1)[0]
253
+ drive_url = f"https://drive.google.com/uc?export=download&id={file_id}"
254
+ filename = None
255
+
256
+ # Start session
257
+ with requests.Session() as session:
258
+ response = session.get(drive_url, stream=True)
259
+ if "quota exceeded" in str(response.content.lower()):
260
+ raise ConnectionError(
261
+ emojis(
262
+ f"❌ Google Drive file download quota exceeded. "
263
+ f"Please try again later or download this file manually at {link}."
264
+ )
265
+ )
266
+ for k, v in response.cookies.items():
267
+ if k.startswith("download_warning"):
268
+ drive_url += f"&confirm={v}" # v is token
269
+ if cd := response.headers.get("content-disposition"):
270
+ filename = re.findall('filename="(.+)"', cd)[0]
271
+ return drive_url, filename
272
+
273
+
274
+ def safe_download(
275
+ url: str | Path,
276
+ file: str | Path | None = None,
277
+ dir: str | Path | None = None,
278
+ unzip: bool = True,
279
+ delete: bool = False,
280
+ curl: bool = False,
281
+ retry: int = 3,
282
+ min_bytes: float = 1e0,
283
+ exist_ok: bool = False,
284
+ progress: bool = True,
285
+ ) -> Path | str:
286
+ """Download files from a URL with options for retrying, unzipping, and deleting the downloaded file. Enhanced with
287
+ robust partial download detection using Content-Length validation.
288
+
289
+ Args:
290
+ url (str): The URL of the file to be downloaded.
291
+ file (str, optional): The filename of the downloaded file. If not provided, the file will be saved with the same
292
+ name as the URL.
293
+ dir (str | Path, optional): The directory to save the downloaded file. If not provided, the file will be saved
294
+ in the current working directory.
295
+ unzip (bool, optional): Whether to unzip the downloaded file.
296
+ delete (bool, optional): Whether to delete the downloaded file after unzipping.
297
+ curl (bool, optional): Whether to use curl command line tool for downloading.
298
+ retry (int, optional): The number of times to retry the download in case of failure.
299
+ min_bytes (float, optional): The minimum number of bytes that the downloaded file should have, to be considered
300
+ a successful download.
301
+ exist_ok (bool, optional): Whether to overwrite existing contents during unzipping.
302
+ progress (bool, optional): Whether to display a progress bar during the download.
303
+
304
+ Returns:
305
+ (Path | str): The path to the downloaded file or extracted directory.
306
+
307
+ Examples:
308
+ >>> from ultralytics.utils.downloads import safe_download
309
+ >>> link = "https://ultralytics.com/assets/bus.jpg"
310
+ >>> path = safe_download(link)
311
+ """
312
+ gdrive = url.startswith("https://drive.google.com/") # check if the URL is a Google Drive link
313
+ if gdrive:
314
+ url, file = get_google_drive_file_info(url)
315
+
316
+ f = Path(dir or ".") / (file or url2file(url)) # URL converted to filename
317
+ if "://" not in str(url) and Path(url).is_file(): # URL exists ('://' check required in Windows Python<3.10)
318
+ f = Path(url) # filename
319
+ elif not f.is_file(): # URL and file do not exist
320
+ uri = (url if gdrive else clean_url(url)).replace(ASSETS_URL, "https://ultralytics.com/assets") # clean
321
+ desc = f"Downloading {uri} to '{f}'"
322
+ f.parent.mkdir(parents=True, exist_ok=True) # make directory if missing
323
+ curl_installed = shutil.which("curl")
324
+ for i in range(retry + 1):
325
+ try:
326
+ if (curl or i > 0) and curl_installed: # curl download with retry, continue
327
+ s = "sS" * (not progress) # silent
328
+ r = subprocess.run(["curl", "-#", f"-{s}L", url, "-o", f, "--retry", "3", "-C", "-"]).returncode
329
+ assert r == 0, f"Curl return value {r}"
330
+ expected_size = None # Can't get size with curl
331
+ else: # urllib download
332
+ with request.urlopen(url) as response:
333
+ expected_size = int(response.getheader("Content-Length", 0))
334
+ if i == 0 and expected_size > 1048576:
335
+ check_disk_space(expected_size, path=f.parent)
336
+ buffer_size = max(8192, min(1048576, expected_size // 1000)) if expected_size else 8192
337
+ with TQDM(
338
+ total=expected_size,
339
+ desc=desc,
340
+ disable=not progress,
341
+ unit="B",
342
+ unit_scale=True,
343
+ unit_divisor=1024,
344
+ ) as pbar:
345
+ with open(f, "wb") as f_opened:
346
+ while True:
347
+ data = response.read(buffer_size)
348
+ if not data:
349
+ break
350
+ f_opened.write(data)
351
+ pbar.update(len(data))
352
+
353
+ if f.exists():
354
+ file_size = f.stat().st_size
355
+ if file_size > min_bytes:
356
+ # Check if download is complete (only if we have expected_size)
357
+ if expected_size and file_size != expected_size:
358
+ LOGGER.warning(
359
+ f"Partial download: {file_size}/{expected_size} bytes ({file_size / expected_size * 100:.1f}%)"
360
+ )
361
+ else:
362
+ break # success
363
+ f.unlink() # remove partial downloads
364
+ except MemoryError:
365
+ raise # Re-raise immediately - no point retrying if insufficient disk space
366
+ except Exception as e:
367
+ if i == 0 and not is_online():
368
+ raise ConnectionError(emojis(f"❌ Download failure for {uri}. Environment may be offline.")) from e
369
+ elif i >= retry:
370
+ raise ConnectionError(emojis(f"❌ Download failure for {uri}. Retry limit reached. {e}")) from e
371
+ LOGGER.warning(f"Download failure, retrying {i + 1}/{retry} {uri}... {e}")
372
+
373
+ if unzip and f.exists() and f.suffix in {"", ".zip", ".tar", ".gz"}:
374
+ from zipfile import is_zipfile
375
+
376
+ unzip_dir = (dir or f.parent).resolve() # unzip to dir if provided else unzip in place
377
+ if is_zipfile(f):
378
+ unzip_dir = unzip_file(file=f, path=unzip_dir, exist_ok=exist_ok, progress=progress) # unzip
379
+ elif f.suffix in {".tar", ".gz"}:
380
+ LOGGER.info(f"Unzipping {f} to {unzip_dir}...")
381
+ subprocess.run(["tar", "xf" if f.suffix == ".tar" else "xfz", f, "--directory", unzip_dir], check=True)
382
+ if delete:
383
+ f.unlink() # remove zip
384
+ return unzip_dir
385
+ return f
386
+
387
+
388
+ def get_github_assets(
389
+ repo: str = "ultralytics/assets",
390
+ version: str = "latest",
391
+ retry: bool = False,
392
+ ) -> tuple[str, list[str]]:
393
+ """Retrieve the specified version's tag and assets from a GitHub repository.
394
+
395
+ If the version is not specified, the function fetches the latest release assets.
396
+
397
+ Args:
398
+ repo (str, optional): The GitHub repository in the format 'owner/repo'.
399
+ version (str, optional): The release version to fetch assets from.
400
+ retry (bool, optional): Flag to retry the request in case of a failure.
401
+
402
+ Returns:
403
+ tag (str): The release tag.
404
+ assets (list[str]): A list of asset names.
405
+
406
+ Examples:
407
+ >>> tag, assets = get_github_assets(repo="ultralytics/assets", version="latest")
408
+ """
409
+ import requests # scoped as slow import
410
+
411
+ if version != "latest":
412
+ version = f"tags/{version}" # i.e. tags/v6.2
413
+ url = f"https://api.github.com/repos/{repo}/releases/{version}"
414
+ r = requests.get(url) # github api
415
+ if r.status_code != 200 and r.reason != "rate limit exceeded" and retry: # failed and not 403 rate limit exceeded
416
+ r = requests.get(url) # try again
417
+ if r.status_code != 200:
418
+ LOGGER.warning(f"GitHub assets check failure for {url}: {r.status_code} {r.reason}")
419
+ return "", []
420
+ data = r.json()
421
+ return data["tag_name"], [x["name"] for x in data["assets"]] # tag, assets i.e. ['yolo11n.pt', 'yolov8s.pt', ...]
422
+
423
+
424
+ def attempt_download_asset(
425
+ file: str | Path,
426
+ repo: str = "ultralytics/assets",
427
+ release: str = "v8.3.0",
428
+ **kwargs,
429
+ ) -> str:
430
+ """Attempt to download a file from GitHub release assets if it is not found locally.
431
+
432
+ Args:
433
+ file (str | Path): The filename or file path to be downloaded.
434
+ repo (str, optional): The GitHub repository in the format 'owner/repo'.
435
+ release (str, optional): The specific release version to be downloaded.
436
+ **kwargs (Any): Additional keyword arguments for the download process.
437
+
438
+ Returns:
439
+ (str): The path to the downloaded file.
440
+
441
+ Examples:
442
+ >>> file_path = attempt_download_asset("yolo11n.pt", repo="ultralytics/assets", release="latest")
443
+ """
444
+ from ultralytics.utils import SETTINGS # scoped for circular import
445
+
446
+ # YOLOv3/5u updates
447
+ file = str(file)
448
+ file = checks.check_yolov5u_filename(file)
449
+ file = Path(file.strip().replace("'", ""))
450
+ if file.exists():
451
+ return str(file)
452
+ elif (SETTINGS["weights_dir"] / file).exists():
453
+ return str(SETTINGS["weights_dir"] / file)
454
+ else:
455
+ # URL specified
456
+ name = Path(parse.unquote(str(file))).name # decode '%2F' to '/' etc.
457
+ download_url = f"https://github.com/{repo}/releases/download"
458
+ if str(file).startswith(("http:/", "https:/")): # download
459
+ url = str(file).replace(":/", "://") # Pathlib turns :// -> :/
460
+ file = url2file(name) # parse authentication https://url.com/file.txt?auth...
461
+ if Path(file).is_file():
462
+ LOGGER.info(f"Found {clean_url(url)} locally at {file}") # file already exists
463
+ else:
464
+ safe_download(url=url, file=file, min_bytes=1e5, **kwargs)
465
+
466
+ elif repo == GITHUB_ASSETS_REPO and name in GITHUB_ASSETS_NAMES:
467
+ safe_download(url=f"{download_url}/{release}/{name}", file=file, min_bytes=1e5, **kwargs)
468
+
469
+ else:
470
+ tag, assets = get_github_assets(repo, release)
471
+ if not assets:
472
+ tag, assets = get_github_assets(repo) # latest release
473
+ if name in assets:
474
+ safe_download(url=f"{download_url}/{tag}/{name}", file=file, min_bytes=1e5, **kwargs)
475
+
476
+ return str(file)
477
+
478
+
479
+ def download(
480
+ url: str | list[str] | Path,
481
+ dir: Path = Path.cwd(),
482
+ unzip: bool = True,
483
+ delete: bool = False,
484
+ curl: bool = False,
485
+ threads: int = 1,
486
+ retry: int = 3,
487
+ exist_ok: bool = False,
488
+ ) -> None:
489
+ """Download files from specified URLs to a given directory.
490
+
491
+ Supports concurrent downloads if multiple threads are specified.
492
+
493
+ Args:
494
+ url (str | list[str]): The URL or list of URLs of the files to be downloaded.
495
+ dir (Path, optional): The directory where the files will be saved.
496
+ unzip (bool, optional): Flag to unzip the files after downloading.
497
+ delete (bool, optional): Flag to delete the zip files after extraction.
498
+ curl (bool, optional): Flag to use curl for downloading.
499
+ threads (int, optional): Number of threads to use for concurrent downloads.
500
+ retry (int, optional): Number of retries in case of download failure.
501
+ exist_ok (bool, optional): Whether to overwrite existing contents during unzipping.
502
+
503
+ Examples:
504
+ >>> download("https://ultralytics.com/assets/example.zip", dir="path/to/dir", unzip=True)
505
+ """
506
+ dir = Path(dir)
507
+ dir.mkdir(parents=True, exist_ok=True) # make directory
508
+ urls = [url] if isinstance(url, (str, Path)) else url
509
+ if threads > 1:
510
+ LOGGER.info(f"Downloading {len(urls)} file(s) with {threads} threads to {dir}...")
511
+ with ThreadPool(threads) as pool:
512
+ pool.map(
513
+ lambda x: safe_download(
514
+ url=x[0],
515
+ dir=x[1],
516
+ unzip=unzip,
517
+ delete=delete,
518
+ curl=curl,
519
+ retry=retry,
520
+ exist_ok=exist_ok,
521
+ progress=True,
522
+ ),
523
+ zip(urls, repeat(dir)),
524
+ )
525
+ pool.close()
526
+ pool.join()
527
+ else:
528
+ for u in urls:
529
+ safe_download(url=u, dir=dir, unzip=unzip, delete=delete, curl=curl, retry=retry, exist_ok=exist_ok)
@@ -0,0 +1,35 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from ultralytics.utils import emojis
4
+
5
+
6
+ class HUBModelError(Exception):
7
+ """Exception raised when a model cannot be found or retrieved from Ultralytics HUB.
8
+
9
+ This custom exception is used specifically for handling errors related to model fetching in Ultralytics YOLO. The
10
+ error message is processed to include emojis for better user experience.
11
+
12
+ Attributes:
13
+ message (str): The error message displayed when the exception is raised.
14
+
15
+ Methods:
16
+ __init__: Initialize the HUBModelError with a custom message.
17
+
18
+ Examples:
19
+ >>> try:
20
+ ... # Code that might fail to find a model
21
+ ... raise HUBModelError("Custom model not found message")
22
+ ... except HUBModelError as e:
23
+ ... print(e) # Displays the emoji-enhanced error message
24
+ """
25
+
26
+ def __init__(self, message: str = "Model not found. Please check model URL and try again."):
27
+ """Initialize a HUBModelError exception.
28
+
29
+ This exception is raised when a requested model is not found or cannot be retrieved from Ultralytics HUB. The
30
+ message is processed to include emojis for better user experience.
31
+
32
+ Args:
33
+ message (str, optional): The error message to display when the exception is raised.
34
+ """
35
+ super().__init__(emojis(message))
@@ -0,0 +1,113 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import json
4
+ import random
5
+ import time
6
+ from pathlib import Path
7
+ from threading import Thread
8
+ from urllib.request import Request, urlopen
9
+
10
+ from ultralytics import SETTINGS, __version__
11
+ from ultralytics.utils import ARGV, ENVIRONMENT, GIT, IS_PIP_PACKAGE, ONLINE, PYTHON_VERSION, RANK, TESTS_RUNNING
12
+ from ultralytics.utils.downloads import GITHUB_ASSETS_NAMES
13
+ from ultralytics.utils.torch_utils import get_cpu_info
14
+
15
+
16
+ def _post(url: str, data: dict, timeout: float = 5.0) -> None:
17
+ """Send a one-shot JSON POST request."""
18
+ try:
19
+ body = json.dumps(data, separators=(",", ":")).encode() # compact JSON
20
+ req = Request(url, data=body, headers={"Content-Type": "application/json"})
21
+ urlopen(req, timeout=timeout).close()
22
+ except Exception:
23
+ pass
24
+
25
+
26
+ class Events:
27
+ """Collect and send anonymous usage analytics with rate-limiting.
28
+
29
+ Event collection and transmission are enabled when sync is enabled in settings, the current process is rank -1 or 0,
30
+ tests are not running, the environment is online, and the installation source is either pip or the official
31
+ Ultralytics GitHub repository.
32
+
33
+ Attributes:
34
+ url (str): Measurement Protocol endpoint for receiving anonymous events.
35
+ events (list[dict]): In-memory queue of event payloads awaiting transmission.
36
+ rate_limit (float): Minimum time in seconds between POST requests.
37
+ t (float): Timestamp of the last transmission in seconds since the epoch.
38
+ metadata (dict): Static metadata describing runtime, installation source, and environment.
39
+ enabled (bool): Flag indicating whether analytics collection is active.
40
+
41
+ Methods:
42
+ __init__: Initialize the event queue, rate limiter, and runtime metadata.
43
+ __call__: Queue an event and trigger a non-blocking send when the rate limit elapses.
44
+ """
45
+
46
+ url = "https://www.google-analytics.com/mp/collect?measurement_id=G-X8NCJYTQXM&api_secret=QLQrATrNSwGRFRLE-cbHJw"
47
+
48
+ def __init__(self) -> None:
49
+ """Initialize the Events instance with queue, rate limiter, and environment metadata."""
50
+ self.events = [] # pending events
51
+ self.rate_limit = 30.0 # rate limit (seconds)
52
+ self.t = 0.0 # last send timestamp (seconds)
53
+ self.metadata = {
54
+ "cli": Path(ARGV[0]).name == "yolo",
55
+ "install": "git" if GIT.is_repo else "pip" if IS_PIP_PACKAGE else "other",
56
+ "python": PYTHON_VERSION.rsplit(".", 1)[0], # i.e. 3.13
57
+ "CPU": get_cpu_info(),
58
+ # "GPU": get_gpu_info(index=0) if cuda else None,
59
+ "version": __version__,
60
+ "env": ENVIRONMENT,
61
+ "session_id": round(random.random() * 1e15),
62
+ "engagement_time_msec": 1000,
63
+ }
64
+ self.enabled = (
65
+ SETTINGS["sync"]
66
+ and RANK in {-1, 0}
67
+ and not TESTS_RUNNING
68
+ and ONLINE
69
+ and (IS_PIP_PACKAGE or GIT.origin == "https://github.com/ultralytics/ultralytics.git")
70
+ )
71
+
72
+ def __call__(self, cfg, device=None) -> None:
73
+ """Queue an event and flush the queue asynchronously when the rate limit elapses.
74
+
75
+ Args:
76
+ cfg (IterableSimpleNamespace): The configuration object containing mode and task information.
77
+ device (torch.device | str, optional): The device type (e.g., 'cpu', 'cuda').
78
+ """
79
+ if not self.enabled:
80
+ # Events disabled, do nothing
81
+ return
82
+
83
+ # Attempt to enqueue a new event
84
+ if len(self.events) < 25: # Queue limited to 25 events to bound memory and traffic
85
+ params = {
86
+ **self.metadata,
87
+ "task": cfg.task,
88
+ "model": cfg.model if cfg.model in GITHUB_ASSETS_NAMES else "custom",
89
+ "device": str(device),
90
+ }
91
+ if cfg.mode == "export":
92
+ params["format"] = cfg.format
93
+ self.events.append({"name": cfg.mode, "params": params})
94
+
95
+ # Check rate limit and return early if under limit
96
+ t = time.time()
97
+ if (t - self.t) < self.rate_limit:
98
+ return
99
+
100
+ # Overrate limit: send a snapshot of queued events in a background thread
101
+ payload_events = list(self.events) # snapshot to avoid race with queue reset
102
+ Thread(
103
+ target=_post,
104
+ args=(self.url, {"client_id": SETTINGS["uuid"], "events": payload_events}), # SHA-256 anonymized
105
+ daemon=True,
106
+ ).start()
107
+
108
+ # Reset queue and rate limit timer
109
+ self.events = []
110
+ self.t = t
111
+
112
+
113
+ events = Events()
@@ -0,0 +1,7 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from .engine import onnx2engine, torch2onnx
4
+ from .imx import torch2imx
5
+ from .tensorflow import keras2pb, onnx2saved_model, pb2tfjs, tflite2edgetpu
6
+
7
+ __all__ = ["keras2pb", "onnx2engine", "onnx2saved_model", "pb2tfjs", "tflite2edgetpu", "torch2imx", "torch2onnx"]