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,168 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import requests
4
+
5
+ from ultralytics.data.utils import HUBDatasetStats
6
+ from ultralytics.hub.auth import Auth
7
+ from ultralytics.hub.session import HUBTrainingSession
8
+ from ultralytics.hub.utils import HUB_API_ROOT, HUB_WEB_ROOT, PREFIX, events
9
+ from ultralytics.utils import LOGGER, SETTINGS, checks
10
+
11
+ __all__ = (
12
+ "PREFIX",
13
+ "HUB_WEB_ROOT",
14
+ "HUBTrainingSession",
15
+ "login",
16
+ "logout",
17
+ "reset_model",
18
+ "export_fmts_hub",
19
+ "export_model",
20
+ "get_export",
21
+ "check_dataset",
22
+ "events",
23
+ )
24
+
25
+
26
+ def login(api_key: str = None, save: bool = True) -> bool:
27
+ """
28
+ Log in to the Ultralytics HUB API using the provided API key.
29
+
30
+ The session is not stored; a new session is created when needed using the saved SETTINGS or the HUB_API_KEY
31
+ environment variable if successfully authenticated.
32
+
33
+ Args:
34
+ api_key (str, optional): API key to use for authentication. If not provided, it will be retrieved from SETTINGS
35
+ or HUB_API_KEY environment variable.
36
+ save (bool, optional): Whether to save the API key to SETTINGS if authentication is successful.
37
+
38
+ Returns:
39
+ (bool): True if authentication is successful, False otherwise.
40
+ """
41
+ checks.check_requirements("hub-sdk>=0.0.12")
42
+ from hub_sdk import HUBClient
43
+
44
+ api_key_url = f"{HUB_WEB_ROOT}/settings?tab=api+keys" # set the redirect URL
45
+ saved_key = SETTINGS.get("api_key")
46
+ active_key = api_key or saved_key
47
+ credentials = {"api_key": active_key} if active_key and active_key != "" else None # set credentials
48
+
49
+ client = HUBClient(credentials) # initialize HUBClient
50
+
51
+ if client.authenticated:
52
+ # Successfully authenticated with HUB
53
+
54
+ if save and client.api_key != saved_key:
55
+ SETTINGS.update({"api_key": client.api_key}) # update settings with valid API key
56
+
57
+ # Set message based on whether key was provided or retrieved from settings
58
+ log_message = (
59
+ "New authentication successful ✅" if client.api_key == api_key or not credentials else "Authenticated ✅"
60
+ )
61
+ LOGGER.info(f"{PREFIX}{log_message}")
62
+
63
+ return True
64
+ else:
65
+ # Failed to authenticate with HUB
66
+ LOGGER.info(f"{PREFIX}Get API key from {api_key_url} and then run 'yolo login API_KEY'")
67
+ return False
68
+
69
+
70
+ def logout():
71
+ """
72
+ Log out of Ultralytics HUB by removing the API key from the settings file. To log in again, use 'yolo login'.
73
+
74
+ Examples:
75
+ >>> from ultralytics import hub
76
+ >>> hub.logout()
77
+ """
78
+ SETTINGS["api_key"] = ""
79
+ LOGGER.info(f"{PREFIX}logged out ✅. To log in again, use 'yolo login'.")
80
+
81
+
82
+ def reset_model(model_id: str = ""):
83
+ """Reset a trained model to an untrained state."""
84
+ r = requests.post(f"{HUB_API_ROOT}/model-reset", json={"modelId": model_id}, headers={"x-api-key": Auth().api_key})
85
+ if r.status_code == 200:
86
+ LOGGER.info(f"{PREFIX}Model reset successfully")
87
+ return
88
+ LOGGER.warning(f"{PREFIX}Model reset failure {r.status_code} {r.reason}")
89
+
90
+
91
+ def export_fmts_hub():
92
+ """Returns a list of HUB-supported export formats."""
93
+ from ultralytics.engine.exporter import export_formats
94
+
95
+ return list(export_formats()["Argument"][1:]) + ["ultralytics_tflite", "ultralytics_coreml"]
96
+
97
+
98
+ def export_model(model_id: str = "", format: str = "torchscript"):
99
+ """
100
+ Export a model to a specified format for deployment via the Ultralytics HUB API.
101
+
102
+ Args:
103
+ model_id (str): The ID of the model to export. An empty string will use the default model.
104
+ format (str): The format to export the model to. Must be one of the supported formats returned by
105
+ export_fmts_hub().
106
+
107
+ Raises:
108
+ AssertionError: If the specified format is not supported or if the export request fails.
109
+
110
+ Examples:
111
+ >>> from ultralytics import hub
112
+ >>> hub.export_model(model_id="your_model_id", format="torchscript")
113
+ """
114
+ assert format in export_fmts_hub(), f"Unsupported export format '{format}', valid formats are {export_fmts_hub()}"
115
+ r = requests.post(
116
+ f"{HUB_API_ROOT}/v1/models/{model_id}/export", json={"format": format}, headers={"x-api-key": Auth().api_key}
117
+ )
118
+ assert r.status_code == 200, f"{PREFIX}{format} export failure {r.status_code} {r.reason}"
119
+ LOGGER.info(f"{PREFIX}{format} export started ✅")
120
+
121
+
122
+ def get_export(model_id: str = "", format: str = "torchscript"):
123
+ """
124
+ Retrieve an exported model in the specified format from Ultralytics HUB using the model ID.
125
+
126
+ Args:
127
+ model_id (str): The ID of the model to retrieve from Ultralytics HUB.
128
+ format (str): The export format to retrieve. Must be one of the supported formats returned by export_fmts_hub().
129
+
130
+ Raises:
131
+ AssertionError: If the specified format is not supported or if the API request fails.
132
+
133
+ Examples:
134
+ >>> from ultralytics import hub
135
+ >>> hub.get_export(model_id="your_model_id", format="torchscript")
136
+ """
137
+ assert format in export_fmts_hub(), f"Unsupported export format '{format}', valid formats are {export_fmts_hub()}"
138
+ r = requests.post(
139
+ f"{HUB_API_ROOT}/get-export",
140
+ json={"apiKey": Auth().api_key, "modelId": model_id, "format": format},
141
+ headers={"x-api-key": Auth().api_key},
142
+ )
143
+ assert r.status_code == 200, f"{PREFIX}{format} get_export failure {r.status_code} {r.reason}"
144
+ return r.json()
145
+
146
+
147
+ def check_dataset(path: str, task: str) -> None:
148
+ """
149
+ Check HUB dataset Zip file for errors before upload.
150
+
151
+ Args:
152
+ path (str): Path to data.zip (with data.yaml inside data.zip).
153
+ task (str): Dataset task. Options are 'detect', 'segment', 'pose', 'classify', 'obb'.
154
+
155
+ Examples:
156
+ >>> from ultralytics.hub import check_dataset
157
+ >>> check_dataset("path/to/coco8.zip", task="detect") # detect dataset
158
+ >>> check_dataset("path/to/coco8-seg.zip", task="segment") # segment dataset
159
+ >>> check_dataset("path/to/coco8-pose.zip", task="pose") # pose dataset
160
+ >>> check_dataset("path/to/dota8.zip", task="obb") # OBB dataset
161
+ >>> check_dataset("path/to/imagenet10.zip", task="classify") # classification dataset
162
+
163
+ Note:
164
+ Download *.zip files from https://github.com/ultralytics/hub/tree/main/example_datasets
165
+ i.e. https://github.com/ultralytics/hub/raw/main/example_datasets/coco8.zip for coco8.zip.
166
+ """
167
+ HUBDatasetStats(path=path, task=task).get_json()
168
+ LOGGER.info(f"Checks completed correctly ✅. Upload this dataset to {HUB_WEB_ROOT}/datasets/.")
@@ -0,0 +1,137 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import requests
4
+
5
+ from ultralytics.hub.utils import HUB_API_ROOT, HUB_WEB_ROOT, PREFIX, request_with_credentials
6
+ from ultralytics.utils import IS_COLAB, LOGGER, SETTINGS, emojis
7
+
8
+ API_KEY_URL = f"{HUB_WEB_ROOT}/settings?tab=api+keys"
9
+
10
+
11
+ class Auth:
12
+ """
13
+ Manages authentication processes including API key handling, cookie-based authentication, and header generation.
14
+
15
+ The class supports different methods of authentication:
16
+ 1. Directly using an API key.
17
+ 2. Authenticating using browser cookies (specifically in Google Colab).
18
+ 3. Prompting the user to enter an API key.
19
+
20
+ Attributes:
21
+ id_token (str | bool): Token used for identity verification, initialized as False.
22
+ api_key (str | bool): API key for authentication, initialized as False.
23
+ model_key (bool): Placeholder for model key, initialized as False.
24
+ """
25
+
26
+ id_token = api_key = model_key = False
27
+
28
+ def __init__(self, api_key: str = "", verbose: bool = False):
29
+ """
30
+ Initialize Auth class and authenticate user.
31
+
32
+ Handles API key validation, Google Colab authentication, and new key requests. Updates SETTINGS upon successful
33
+ authentication.
34
+
35
+ Args:
36
+ api_key (str): API key or combined key_id format.
37
+ verbose (bool): Enable verbose logging.
38
+ """
39
+ # Split the input API key in case it contains a combined key_model and keep only the API key part
40
+ api_key = api_key.split("_")[0]
41
+
42
+ # Set API key attribute as value passed or SETTINGS API key if none passed
43
+ self.api_key = api_key or SETTINGS.get("api_key", "")
44
+
45
+ # If an API key is provided
46
+ if self.api_key:
47
+ # If the provided API key matches the API key in the SETTINGS
48
+ if self.api_key == SETTINGS.get("api_key"):
49
+ # Log that the user is already logged in
50
+ if verbose:
51
+ LOGGER.info(f"{PREFIX}Authenticated ✅")
52
+ return
53
+ else:
54
+ # Attempt to authenticate with the provided API key
55
+ success = self.authenticate()
56
+ # If the API key is not provided and the environment is a Google Colab notebook
57
+ elif IS_COLAB:
58
+ # Attempt to authenticate using browser cookies
59
+ success = self.auth_with_cookies()
60
+ else:
61
+ # Request an API key
62
+ success = self.request_api_key()
63
+
64
+ # Update SETTINGS with the new API key after successful authentication
65
+ if success:
66
+ SETTINGS.update({"api_key": self.api_key})
67
+ # Log that the new login was successful
68
+ if verbose:
69
+ LOGGER.info(f"{PREFIX}New authentication successful ✅")
70
+ elif verbose:
71
+ LOGGER.info(f"{PREFIX}Get API key from {API_KEY_URL} and then run 'yolo login API_KEY'")
72
+
73
+ def request_api_key(self, max_attempts: int = 3) -> bool:
74
+ """Prompt the user to input their API key."""
75
+ import getpass
76
+
77
+ for attempts in range(max_attempts):
78
+ LOGGER.info(f"{PREFIX}Login. Attempt {attempts + 1} of {max_attempts}")
79
+ input_key = getpass.getpass(f"Enter API key from {API_KEY_URL} ")
80
+ self.api_key = input_key.split("_")[0] # remove model id if present
81
+ if self.authenticate():
82
+ return True
83
+ raise ConnectionError(emojis(f"{PREFIX}Failed to authenticate ❌"))
84
+
85
+ def authenticate(self) -> bool:
86
+ """
87
+ Attempt to authenticate with the server using either id_token or API key.
88
+
89
+ Returns:
90
+ (bool): True if authentication is successful, False otherwise.
91
+ """
92
+ try:
93
+ if header := self.get_auth_header():
94
+ r = requests.post(f"{HUB_API_ROOT}/v1/auth", headers=header)
95
+ if not r.json().get("success", False):
96
+ raise ConnectionError("Unable to authenticate.")
97
+ return True
98
+ raise ConnectionError("User has not authenticated locally.")
99
+ except ConnectionError:
100
+ self.id_token = self.api_key = False # reset invalid
101
+ LOGGER.warning(f"{PREFIX}Invalid API key")
102
+ return False
103
+
104
+ def auth_with_cookies(self) -> bool:
105
+ """
106
+ Attempt to fetch authentication via cookies and set id_token.
107
+
108
+ User must be logged in to HUB and running in a supported browser.
109
+
110
+ Returns:
111
+ (bool): True if authentication is successful, False otherwise.
112
+ """
113
+ if not IS_COLAB:
114
+ return False # Currently only works with Colab
115
+ try:
116
+ authn = request_with_credentials(f"{HUB_API_ROOT}/v1/auth/auto")
117
+ if authn.get("success", False):
118
+ self.id_token = authn.get("data", {}).get("idToken", None)
119
+ self.authenticate()
120
+ return True
121
+ raise ConnectionError("Unable to fetch browser authentication details.")
122
+ except ConnectionError:
123
+ self.id_token = False # reset invalid
124
+ return False
125
+
126
+ def get_auth_header(self):
127
+ """
128
+ Get the authentication header for making API requests.
129
+
130
+ Returns:
131
+ (dict | None): The authentication header if id_token or API key is set, None otherwise.
132
+ """
133
+ if self.id_token:
134
+ return {"authorization": f"Bearer {self.id_token}"}
135
+ elif self.api_key:
136
+ return {"x-api-key": self.api_key}
137
+ # else returns None
@@ -0,0 +1,176 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import concurrent.futures
4
+ import statistics
5
+ import time
6
+ from typing import List, Optional, Tuple
7
+
8
+ import requests
9
+
10
+
11
+ class GCPRegions:
12
+ """
13
+ A class for managing and analyzing Google Cloud Platform (GCP) regions.
14
+
15
+ This class provides functionality to initialize, categorize, and analyze GCP regions based on their
16
+ geographical location, tier classification, and network latency.
17
+
18
+ Attributes:
19
+ regions (Dict[str, Tuple[int, str, str]]): A dictionary of GCP regions with their tier, city, and country.
20
+
21
+ Methods:
22
+ tier1: Returns a list of tier 1 GCP regions.
23
+ tier2: Returns a list of tier 2 GCP regions.
24
+ lowest_latency: Determines the GCP region(s) with the lowest network latency.
25
+
26
+ Examples:
27
+ >>> from ultralytics.hub.google import GCPRegions
28
+ >>> regions = GCPRegions()
29
+ >>> lowest_latency_region = regions.lowest_latency(verbose=True, attempts=3)
30
+ >>> print(f"Lowest latency region: {lowest_latency_region[0][0]}")
31
+ """
32
+
33
+ def __init__(self):
34
+ """Initializes the GCPRegions class with predefined Google Cloud Platform regions and their details."""
35
+ self.regions = {
36
+ "asia-east1": (1, "Taiwan", "China"),
37
+ "asia-east2": (2, "Hong Kong", "China"),
38
+ "asia-northeast1": (1, "Tokyo", "Japan"),
39
+ "asia-northeast2": (1, "Osaka", "Japan"),
40
+ "asia-northeast3": (2, "Seoul", "South Korea"),
41
+ "asia-south1": (2, "Mumbai", "India"),
42
+ "asia-south2": (2, "Delhi", "India"),
43
+ "asia-southeast1": (2, "Jurong West", "Singapore"),
44
+ "asia-southeast2": (2, "Jakarta", "Indonesia"),
45
+ "australia-southeast1": (2, "Sydney", "Australia"),
46
+ "australia-southeast2": (2, "Melbourne", "Australia"),
47
+ "europe-central2": (2, "Warsaw", "Poland"),
48
+ "europe-north1": (1, "Hamina", "Finland"),
49
+ "europe-southwest1": (1, "Madrid", "Spain"),
50
+ "europe-west1": (1, "St. Ghislain", "Belgium"),
51
+ "europe-west10": (2, "Berlin", "Germany"),
52
+ "europe-west12": (2, "Turin", "Italy"),
53
+ "europe-west2": (2, "London", "United Kingdom"),
54
+ "europe-west3": (2, "Frankfurt", "Germany"),
55
+ "europe-west4": (1, "Eemshaven", "Netherlands"),
56
+ "europe-west6": (2, "Zurich", "Switzerland"),
57
+ "europe-west8": (1, "Milan", "Italy"),
58
+ "europe-west9": (1, "Paris", "France"),
59
+ "me-central1": (2, "Doha", "Qatar"),
60
+ "me-west1": (1, "Tel Aviv", "Israel"),
61
+ "northamerica-northeast1": (2, "Montreal", "Canada"),
62
+ "northamerica-northeast2": (2, "Toronto", "Canada"),
63
+ "southamerica-east1": (2, "São Paulo", "Brazil"),
64
+ "southamerica-west1": (2, "Santiago", "Chile"),
65
+ "us-central1": (1, "Iowa", "United States"),
66
+ "us-east1": (1, "South Carolina", "United States"),
67
+ "us-east4": (1, "Northern Virginia", "United States"),
68
+ "us-east5": (1, "Columbus", "United States"),
69
+ "us-south1": (1, "Dallas", "United States"),
70
+ "us-west1": (1, "Oregon", "United States"),
71
+ "us-west2": (2, "Los Angeles", "United States"),
72
+ "us-west3": (2, "Salt Lake City", "United States"),
73
+ "us-west4": (2, "Las Vegas", "United States"),
74
+ }
75
+
76
+ def tier1(self) -> List[str]:
77
+ """Returns a list of GCP regions classified as tier 1 based on predefined criteria."""
78
+ return [region for region, info in self.regions.items() if info[0] == 1]
79
+
80
+ def tier2(self) -> List[str]:
81
+ """Returns a list of GCP regions classified as tier 2 based on predefined criteria."""
82
+ return [region for region, info in self.regions.items() if info[0] == 2]
83
+
84
+ @staticmethod
85
+ def _ping_region(region: str, attempts: int = 1) -> Tuple[str, float, float, float, float]:
86
+ """
87
+ Ping a specified GCP region and measure network latency statistics.
88
+
89
+ Args:
90
+ region (str): The GCP region identifier to ping (e.g., 'us-central1').
91
+ attempts (int): Number of ping attempts to make for calculating statistics.
92
+
93
+ Returns:
94
+ region (str): The GCP region identifier that was pinged.
95
+ mean_latency (float): Mean latency in milliseconds, or infinity if all pings failed.
96
+ min_latency (float): Minimum latency in milliseconds, or infinity if all pings failed.
97
+ max_latency (float): Maximum latency in milliseconds, or infinity if all pings failed.
98
+ std_dev (float): Standard deviation of latencies in milliseconds, or infinity if all pings failed.
99
+
100
+ Examples:
101
+ >>> region, mean, min_lat, max_lat, std = GCPRegions._ping_region("us-central1", attempts=3)
102
+ >>> print(f"Region {region} has mean latency: {mean:.2f}ms")
103
+ """
104
+ url = f"https://{region}-docker.pkg.dev"
105
+ latencies = []
106
+ for _ in range(attempts):
107
+ try:
108
+ start_time = time.time()
109
+ _ = requests.head(url, timeout=5)
110
+ latency = (time.time() - start_time) * 1000 # convert latency to milliseconds
111
+ if latency != float("inf"):
112
+ latencies.append(latency)
113
+ except requests.RequestException:
114
+ pass
115
+ if not latencies:
116
+ return region, float("inf"), float("inf"), float("inf"), float("inf")
117
+
118
+ std_dev = statistics.stdev(latencies) if len(latencies) > 1 else 0
119
+ return region, statistics.mean(latencies), std_dev, min(latencies), max(latencies)
120
+
121
+ def lowest_latency(
122
+ self,
123
+ top: int = 1,
124
+ verbose: bool = False,
125
+ tier: Optional[int] = None,
126
+ attempts: int = 1,
127
+ ) -> List[Tuple[str, float, float, float, float]]:
128
+ """
129
+ Determines the GCP regions with the lowest latency based on ping tests.
130
+
131
+ Args:
132
+ top (int): Number of top regions to return.
133
+ verbose (bool): If True, prints detailed latency information for all tested regions.
134
+ tier (int | None): Filter regions by tier (1 or 2). If None, all regions are tested.
135
+ attempts (int): Number of ping attempts per region.
136
+
137
+ Returns:
138
+ (List[Tuple[str, float, float, float, float]]): List of tuples containing region information and
139
+ latency statistics. Each tuple contains (region, mean_latency, std_dev, min_latency, max_latency).
140
+
141
+ Examples:
142
+ >>> regions = GCPRegions()
143
+ >>> results = regions.lowest_latency(top=3, verbose=True, tier=1, attempts=2)
144
+ >>> print(results[0][0]) # Print the name of the lowest latency region
145
+ """
146
+ if verbose:
147
+ print(f"Testing GCP regions for latency (with {attempts} {'retry' if attempts == 1 else 'attempts'})...")
148
+
149
+ regions_to_test = [k for k, v in self.regions.items() if v[0] == tier] if tier else list(self.regions.keys())
150
+ with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
151
+ results = list(executor.map(lambda r: self._ping_region(r, attempts), regions_to_test))
152
+
153
+ sorted_results = sorted(results, key=lambda x: x[1])
154
+
155
+ if verbose:
156
+ print(f"{'Region':<25} {'Location':<35} {'Tier':<5} Latency (ms)")
157
+ for region, mean, std, min_, max_ in sorted_results:
158
+ tier, city, country = self.regions[region]
159
+ location = f"{city}, {country}"
160
+ if mean == float("inf"):
161
+ print(f"{region:<25} {location:<35} {tier:<5} Timeout")
162
+ else:
163
+ print(f"{region:<25} {location:<35} {tier:<5} {mean:.0f} ± {std:.0f} ({min_:.0f} - {max_:.0f})")
164
+ print(f"\nLowest latency region{'s' if top > 1 else ''}:")
165
+ for region, mean, std, min_, max_ in sorted_results[:top]:
166
+ tier, city, country = self.regions[region]
167
+ location = f"{city}, {country}"
168
+ print(f"{region} ({location}, {mean:.0f} ± {std:.0f} ms ({min_:.0f} - {max_:.0f}))")
169
+
170
+ return sorted_results[:top]
171
+
172
+
173
+ # Usage example
174
+ if __name__ == "__main__":
175
+ regions = GCPRegions()
176
+ top_3_latency_tier1 = regions.lowest_latency(top=3, verbose=True, tier=1, attempts=3)