dgenerate-ultralytics-headless 8.3.137__py3-none-any.whl → 8.3.224__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 (215) hide show
  1. {dgenerate_ultralytics_headless-8.3.137.dist-info → dgenerate_ultralytics_headless-8.3.224.dist-info}/METADATA +41 -34
  2. dgenerate_ultralytics_headless-8.3.224.dist-info/RECORD +285 -0
  3. {dgenerate_ultralytics_headless-8.3.137.dist-info → dgenerate_ultralytics_headless-8.3.224.dist-info}/WHEEL +1 -1
  4. tests/__init__.py +7 -6
  5. tests/conftest.py +15 -39
  6. tests/test_cli.py +17 -17
  7. tests/test_cuda.py +17 -8
  8. tests/test_engine.py +36 -10
  9. tests/test_exports.py +98 -37
  10. tests/test_integrations.py +12 -15
  11. tests/test_python.py +126 -82
  12. tests/test_solutions.py +319 -135
  13. ultralytics/__init__.py +27 -9
  14. ultralytics/cfg/__init__.py +83 -87
  15. ultralytics/cfg/datasets/Argoverse.yaml +4 -4
  16. ultralytics/cfg/datasets/DOTAv1.5.yaml +2 -2
  17. ultralytics/cfg/datasets/DOTAv1.yaml +2 -2
  18. ultralytics/cfg/datasets/GlobalWheat2020.yaml +2 -2
  19. ultralytics/cfg/datasets/HomeObjects-3K.yaml +4 -5
  20. ultralytics/cfg/datasets/ImageNet.yaml +3 -3
  21. ultralytics/cfg/datasets/Objects365.yaml +24 -20
  22. ultralytics/cfg/datasets/SKU-110K.yaml +9 -9
  23. ultralytics/cfg/datasets/VOC.yaml +10 -13
  24. ultralytics/cfg/datasets/VisDrone.yaml +43 -33
  25. ultralytics/cfg/datasets/african-wildlife.yaml +5 -5
  26. ultralytics/cfg/datasets/brain-tumor.yaml +4 -5
  27. ultralytics/cfg/datasets/carparts-seg.yaml +5 -5
  28. ultralytics/cfg/datasets/coco-pose.yaml +26 -4
  29. ultralytics/cfg/datasets/coco.yaml +4 -4
  30. ultralytics/cfg/datasets/coco128-seg.yaml +2 -2
  31. ultralytics/cfg/datasets/coco128.yaml +2 -2
  32. ultralytics/cfg/datasets/coco8-grayscale.yaml +103 -0
  33. ultralytics/cfg/datasets/coco8-multispectral.yaml +2 -2
  34. ultralytics/cfg/datasets/coco8-pose.yaml +23 -2
  35. ultralytics/cfg/datasets/coco8-seg.yaml +2 -2
  36. ultralytics/cfg/datasets/coco8.yaml +2 -2
  37. ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
  38. ultralytics/cfg/datasets/crack-seg.yaml +5 -5
  39. ultralytics/cfg/datasets/dog-pose.yaml +32 -4
  40. ultralytics/cfg/datasets/dota8-multispectral.yaml +2 -2
  41. ultralytics/cfg/datasets/dota8.yaml +2 -2
  42. ultralytics/cfg/datasets/hand-keypoints.yaml +29 -4
  43. ultralytics/cfg/datasets/lvis.yaml +9 -9
  44. ultralytics/cfg/datasets/medical-pills.yaml +4 -5
  45. ultralytics/cfg/datasets/open-images-v7.yaml +7 -10
  46. ultralytics/cfg/datasets/package-seg.yaml +5 -5
  47. ultralytics/cfg/datasets/signature.yaml +4 -4
  48. ultralytics/cfg/datasets/tiger-pose.yaml +20 -4
  49. ultralytics/cfg/datasets/xView.yaml +5 -5
  50. ultralytics/cfg/default.yaml +96 -93
  51. ultralytics/cfg/trackers/botsort.yaml +16 -17
  52. ultralytics/cfg/trackers/bytetrack.yaml +9 -11
  53. ultralytics/data/__init__.py +4 -4
  54. ultralytics/data/annotator.py +12 -12
  55. ultralytics/data/augment.py +531 -564
  56. ultralytics/data/base.py +76 -81
  57. ultralytics/data/build.py +206 -42
  58. ultralytics/data/converter.py +179 -78
  59. ultralytics/data/dataset.py +121 -121
  60. ultralytics/data/loaders.py +114 -91
  61. ultralytics/data/split.py +28 -15
  62. ultralytics/data/split_dota.py +67 -48
  63. ultralytics/data/utils.py +110 -89
  64. ultralytics/engine/exporter.py +422 -460
  65. ultralytics/engine/model.py +224 -252
  66. ultralytics/engine/predictor.py +94 -89
  67. ultralytics/engine/results.py +345 -595
  68. ultralytics/engine/trainer.py +231 -134
  69. ultralytics/engine/tuner.py +279 -73
  70. ultralytics/engine/validator.py +53 -46
  71. ultralytics/hub/__init__.py +26 -28
  72. ultralytics/hub/auth.py +30 -16
  73. ultralytics/hub/google/__init__.py +34 -36
  74. ultralytics/hub/session.py +53 -77
  75. ultralytics/hub/utils.py +23 -109
  76. ultralytics/models/__init__.py +1 -1
  77. ultralytics/models/fastsam/__init__.py +1 -1
  78. ultralytics/models/fastsam/model.py +36 -18
  79. ultralytics/models/fastsam/predict.py +33 -44
  80. ultralytics/models/fastsam/utils.py +4 -5
  81. ultralytics/models/fastsam/val.py +12 -14
  82. ultralytics/models/nas/__init__.py +1 -1
  83. ultralytics/models/nas/model.py +16 -20
  84. ultralytics/models/nas/predict.py +12 -14
  85. ultralytics/models/nas/val.py +4 -5
  86. ultralytics/models/rtdetr/__init__.py +1 -1
  87. ultralytics/models/rtdetr/model.py +9 -9
  88. ultralytics/models/rtdetr/predict.py +22 -17
  89. ultralytics/models/rtdetr/train.py +20 -16
  90. ultralytics/models/rtdetr/val.py +79 -59
  91. ultralytics/models/sam/__init__.py +8 -2
  92. ultralytics/models/sam/amg.py +53 -38
  93. ultralytics/models/sam/build.py +29 -31
  94. ultralytics/models/sam/model.py +33 -38
  95. ultralytics/models/sam/modules/blocks.py +159 -182
  96. ultralytics/models/sam/modules/decoders.py +38 -47
  97. ultralytics/models/sam/modules/encoders.py +114 -133
  98. ultralytics/models/sam/modules/memory_attention.py +38 -31
  99. ultralytics/models/sam/modules/sam.py +114 -93
  100. ultralytics/models/sam/modules/tiny_encoder.py +268 -291
  101. ultralytics/models/sam/modules/transformer.py +59 -66
  102. ultralytics/models/sam/modules/utils.py +55 -72
  103. ultralytics/models/sam/predict.py +745 -341
  104. ultralytics/models/utils/loss.py +118 -107
  105. ultralytics/models/utils/ops.py +118 -71
  106. ultralytics/models/yolo/__init__.py +1 -1
  107. ultralytics/models/yolo/classify/predict.py +28 -26
  108. ultralytics/models/yolo/classify/train.py +50 -81
  109. ultralytics/models/yolo/classify/val.py +68 -61
  110. ultralytics/models/yolo/detect/predict.py +12 -15
  111. ultralytics/models/yolo/detect/train.py +56 -46
  112. ultralytics/models/yolo/detect/val.py +279 -223
  113. ultralytics/models/yolo/model.py +167 -86
  114. ultralytics/models/yolo/obb/predict.py +7 -11
  115. ultralytics/models/yolo/obb/train.py +23 -25
  116. ultralytics/models/yolo/obb/val.py +107 -99
  117. ultralytics/models/yolo/pose/__init__.py +1 -1
  118. ultralytics/models/yolo/pose/predict.py +12 -14
  119. ultralytics/models/yolo/pose/train.py +31 -69
  120. ultralytics/models/yolo/pose/val.py +119 -254
  121. ultralytics/models/yolo/segment/predict.py +21 -25
  122. ultralytics/models/yolo/segment/train.py +12 -66
  123. ultralytics/models/yolo/segment/val.py +126 -305
  124. ultralytics/models/yolo/world/train.py +53 -45
  125. ultralytics/models/yolo/world/train_world.py +51 -32
  126. ultralytics/models/yolo/yoloe/__init__.py +7 -7
  127. ultralytics/models/yolo/yoloe/predict.py +30 -37
  128. ultralytics/models/yolo/yoloe/train.py +89 -71
  129. ultralytics/models/yolo/yoloe/train_seg.py +15 -17
  130. ultralytics/models/yolo/yoloe/val.py +56 -41
  131. ultralytics/nn/__init__.py +9 -11
  132. ultralytics/nn/autobackend.py +179 -107
  133. ultralytics/nn/modules/__init__.py +67 -67
  134. ultralytics/nn/modules/activation.py +8 -7
  135. ultralytics/nn/modules/block.py +302 -323
  136. ultralytics/nn/modules/conv.py +61 -104
  137. ultralytics/nn/modules/head.py +488 -186
  138. ultralytics/nn/modules/transformer.py +183 -123
  139. ultralytics/nn/modules/utils.py +15 -20
  140. ultralytics/nn/tasks.py +327 -203
  141. ultralytics/nn/text_model.py +81 -65
  142. ultralytics/py.typed +1 -0
  143. ultralytics/solutions/__init__.py +12 -12
  144. ultralytics/solutions/ai_gym.py +19 -27
  145. ultralytics/solutions/analytics.py +36 -26
  146. ultralytics/solutions/config.py +29 -28
  147. ultralytics/solutions/distance_calculation.py +23 -24
  148. ultralytics/solutions/heatmap.py +17 -19
  149. ultralytics/solutions/instance_segmentation.py +21 -19
  150. ultralytics/solutions/object_blurrer.py +16 -17
  151. ultralytics/solutions/object_counter.py +48 -53
  152. ultralytics/solutions/object_cropper.py +22 -16
  153. ultralytics/solutions/parking_management.py +61 -58
  154. ultralytics/solutions/queue_management.py +19 -19
  155. ultralytics/solutions/region_counter.py +63 -50
  156. ultralytics/solutions/security_alarm.py +22 -25
  157. ultralytics/solutions/similarity_search.py +107 -60
  158. ultralytics/solutions/solutions.py +343 -262
  159. ultralytics/solutions/speed_estimation.py +35 -31
  160. ultralytics/solutions/streamlit_inference.py +104 -40
  161. ultralytics/solutions/templates/similarity-search.html +31 -24
  162. ultralytics/solutions/trackzone.py +24 -24
  163. ultralytics/solutions/vision_eye.py +11 -12
  164. ultralytics/trackers/__init__.py +1 -1
  165. ultralytics/trackers/basetrack.py +18 -27
  166. ultralytics/trackers/bot_sort.py +48 -39
  167. ultralytics/trackers/byte_tracker.py +94 -94
  168. ultralytics/trackers/track.py +7 -16
  169. ultralytics/trackers/utils/gmc.py +37 -69
  170. ultralytics/trackers/utils/kalman_filter.py +68 -76
  171. ultralytics/trackers/utils/matching.py +13 -17
  172. ultralytics/utils/__init__.py +251 -275
  173. ultralytics/utils/autobatch.py +19 -7
  174. ultralytics/utils/autodevice.py +68 -38
  175. ultralytics/utils/benchmarks.py +169 -130
  176. ultralytics/utils/callbacks/base.py +12 -13
  177. ultralytics/utils/callbacks/clearml.py +14 -15
  178. ultralytics/utils/callbacks/comet.py +139 -66
  179. ultralytics/utils/callbacks/dvc.py +19 -27
  180. ultralytics/utils/callbacks/hub.py +8 -6
  181. ultralytics/utils/callbacks/mlflow.py +6 -10
  182. ultralytics/utils/callbacks/neptune.py +11 -19
  183. ultralytics/utils/callbacks/platform.py +73 -0
  184. ultralytics/utils/callbacks/raytune.py +3 -4
  185. ultralytics/utils/callbacks/tensorboard.py +9 -12
  186. ultralytics/utils/callbacks/wb.py +33 -30
  187. ultralytics/utils/checks.py +163 -114
  188. ultralytics/utils/cpu.py +89 -0
  189. ultralytics/utils/dist.py +24 -20
  190. ultralytics/utils/downloads.py +176 -146
  191. ultralytics/utils/errors.py +11 -13
  192. ultralytics/utils/events.py +113 -0
  193. ultralytics/utils/export/__init__.py +7 -0
  194. ultralytics/utils/{export.py → export/engine.py} +81 -63
  195. ultralytics/utils/export/imx.py +294 -0
  196. ultralytics/utils/export/tensorflow.py +217 -0
  197. ultralytics/utils/files.py +33 -36
  198. ultralytics/utils/git.py +137 -0
  199. ultralytics/utils/instance.py +105 -120
  200. ultralytics/utils/logger.py +404 -0
  201. ultralytics/utils/loss.py +99 -61
  202. ultralytics/utils/metrics.py +649 -478
  203. ultralytics/utils/nms.py +337 -0
  204. ultralytics/utils/ops.py +263 -451
  205. ultralytics/utils/patches.py +70 -31
  206. ultralytics/utils/plotting.py +253 -223
  207. ultralytics/utils/tal.py +48 -61
  208. ultralytics/utils/torch_utils.py +244 -251
  209. ultralytics/utils/tqdm.py +438 -0
  210. ultralytics/utils/triton.py +22 -23
  211. ultralytics/utils/tuner.py +11 -10
  212. dgenerate_ultralytics_headless-8.3.137.dist-info/RECORD +0 -272
  213. {dgenerate_ultralytics_headless-8.3.137.dist-info → dgenerate_ultralytics_headless-8.3.224.dist-info}/entry_points.txt +0 -0
  214. {dgenerate_ultralytics_headless-8.3.137.dist-info → dgenerate_ultralytics_headless-8.3.224.dist-info}/licenses/LICENSE +0 -0
  215. {dgenerate_ultralytics_headless-8.3.137.dist-info → dgenerate_ultralytics_headless-8.3.224.dist-info}/top_level.txt +0 -0
@@ -1,14 +1,15 @@
1
1
  # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
2
 
3
+ from __future__ import annotations
4
+
3
5
  import shutil
4
6
  import threading
5
7
  import time
6
8
  from http import HTTPStatus
7
9
  from pathlib import Path
10
+ from typing import Any
8
11
  from urllib.parse import parse_qs, urlparse
9
12
 
10
- import requests
11
-
12
13
  from ultralytics import __version__
13
14
  from ultralytics.hub.utils import HELP_MSG, HUB_WEB_ROOT, PREFIX
14
15
  from ultralytics.utils import IS_COLAB, LOGGER, SETTINGS, TQDM, checks, emojis
@@ -18,8 +19,7 @@ AGENT_NAME = f"python-{__version__}-colab" if IS_COLAB else f"python-{__version_
18
19
 
19
20
 
20
21
  class HUBTrainingSession:
21
- """
22
- HUB training session for Ultralytics HUB YOLO models. Handles model initialization, heartbeats, and checkpointing.
22
+ """HUB training session for Ultralytics HUB YOLO models.
23
23
 
24
24
  This class encapsulates the functionality for interacting with Ultralytics HUB during model training, including
25
25
  model creation, metrics tracking, and checkpoint uploading.
@@ -27,28 +27,28 @@ class HUBTrainingSession:
27
27
  Attributes:
28
28
  model_id (str): Identifier for the YOLO model being trained.
29
29
  model_url (str): URL for the model in Ultralytics HUB.
30
- rate_limits (dict): Rate limits for different API calls (in seconds).
31
- timers (dict): Timers for rate limiting.
32
- metrics_queue (dict): Queue for the model's metrics.
33
- metrics_upload_failed_queue (dict): Queue for metrics that failed to upload.
34
- model (dict): Model data fetched from Ultralytics HUB.
30
+ rate_limits (dict[str, int]): Rate limits for different API calls in seconds.
31
+ timers (dict[str, Any]): Timers for rate limiting.
32
+ metrics_queue (dict[str, Any]): Queue for the model's metrics.
33
+ metrics_upload_failed_queue (dict[str, Any]): Queue for metrics that failed to upload.
34
+ model (Any): Model data fetched from Ultralytics HUB.
35
35
  model_file (str): Path to the model file.
36
- train_args (dict): Arguments for training the model.
37
- client (HUBClient): Client for interacting with Ultralytics HUB.
36
+ train_args (dict[str, Any]): Arguments for training the model.
37
+ client (Any): Client for interacting with Ultralytics HUB.
38
38
  filename (str): Filename of the model.
39
39
 
40
40
  Examples:
41
+ Create a training session with a model URL
41
42
  >>> session = HUBTrainingSession("https://hub.ultralytics.com/models/example-model")
42
43
  >>> session.upload_metrics()
43
44
  """
44
45
 
45
- def __init__(self, identifier):
46
- """
47
- Initialize the HUBTrainingSession with the provided model identifier.
46
+ def __init__(self, identifier: str):
47
+ """Initialize the HUBTrainingSession with the provided model identifier.
48
48
 
49
49
  Args:
50
- identifier (str): Model identifier used to initialize the HUB training session.
51
- It can be a URL string or a model key with specific format.
50
+ identifier (str): Model identifier used to initialize the HUB training session. It can be a URL string or a
51
+ model key with specific format.
52
52
 
53
53
  Raises:
54
54
  ValueError: If the provided model identifier is invalid.
@@ -90,16 +90,15 @@ class HUBTrainingSession:
90
90
  )
91
91
 
92
92
  @classmethod
93
- def create_session(cls, identifier, args=None):
94
- """
95
- Create an authenticated HUBTrainingSession or return None.
93
+ def create_session(cls, identifier: str, args: dict[str, Any] | None = None):
94
+ """Create an authenticated HUBTrainingSession or return None.
96
95
 
97
96
  Args:
98
97
  identifier (str): Model identifier used to initialize the HUB training session.
99
- args (dict, optional): Arguments for creating a new model if identifier is not a HUB model URL.
98
+ args (dict[str, Any], optional): Arguments for creating a new model if identifier is not a HUB model URL.
100
99
 
101
100
  Returns:
102
- (HUBTrainingSession | None): An authenticated session or None if creation fails.
101
+ session (HUBTrainingSession | None): An authenticated session or None if creation fails.
103
102
  """
104
103
  try:
105
104
  session = cls(identifier)
@@ -111,9 +110,8 @@ class HUBTrainingSession:
111
110
  except (PermissionError, ModuleNotFoundError, AssertionError):
112
111
  return None
113
112
 
114
- def load_model(self, model_id):
115
- """
116
- Load an existing model from Ultralytics HUB using the provided model identifier.
113
+ def load_model(self, model_id: str):
114
+ """Load an existing model from Ultralytics HUB using the provided model identifier.
117
115
 
118
116
  Args:
119
117
  model_id (str): The identifier of the model to load.
@@ -137,12 +135,12 @@ class HUBTrainingSession:
137
135
  self.model.start_heartbeat(self.rate_limits["heartbeat"])
138
136
  LOGGER.info(f"{PREFIX}View model at {self.model_url} 🚀")
139
137
 
140
- def create_model(self, model_args):
141
- """
142
- Initialize a HUB training session with the specified model arguments.
138
+ def create_model(self, model_args: dict[str, Any]):
139
+ """Initialize a HUB training session with the specified model arguments.
143
140
 
144
141
  Args:
145
- model_args (dict): Arguments for creating the model, including batch size, epochs, image size, etc.
142
+ model_args (dict[str, Any]): Arguments for creating the model, including batch size, epochs, image size,
143
+ etc.
146
144
 
147
145
  Returns:
148
146
  (None): If the model could not be created.
@@ -182,9 +180,8 @@ class HUBTrainingSession:
182
180
  LOGGER.info(f"{PREFIX}View model at {self.model_url} 🚀")
183
181
 
184
182
  @staticmethod
185
- def _parse_identifier(identifier):
186
- """
187
- Parse the given identifier to determine the type and extract relevant components.
183
+ def _parse_identifier(identifier: str):
184
+ """Parse the given identifier to determine the type and extract relevant components.
188
185
 
189
186
  The method supports different identifier formats:
190
187
  - A HUB model URL https://hub.ultralytics.com/models/MODEL
@@ -195,13 +192,15 @@ class HUBTrainingSession:
195
192
  identifier (str): The identifier string to be parsed.
196
193
 
197
194
  Returns:
198
- (tuple): A tuple containing the API key, model ID, and filename as applicable.
195
+ api_key (str | None): Extracted API key if present.
196
+ model_id (str | None): Extracted model ID if present.
197
+ filename (str | None): Extracted filename if present.
199
198
 
200
199
  Raises:
201
200
  HUBModelError: If the identifier format is not recognized.
202
201
  """
203
202
  api_key, model_id, filename = None, None, None
204
- if str(identifier).endswith((".pt", ".yaml")):
203
+ if identifier.endswith((".pt", ".yaml")):
205
204
  filename = identifier
206
205
  elif identifier.startswith(f"{HUB_WEB_ROOT}/models/"):
207
206
  parsed_url = urlparse(identifier)
@@ -213,12 +212,11 @@ class HUBTrainingSession:
213
212
  return api_key, model_id, filename
214
213
 
215
214
  def _set_train_args(self):
216
- """
217
- Initialize training arguments and create a model entry on the Ultralytics HUB.
215
+ """Initialize training arguments and create a model entry on the Ultralytics HUB.
218
216
 
219
- This method sets up training arguments based on the model's state and updates them with any additional
220
- arguments provided. It handles different states of the model, such as whether it's resumable, pretrained,
221
- or requires specific file setup.
217
+ This method sets up training arguments based on the model's state and updates them with any additional arguments
218
+ provided. It handles different states of the model, such as whether it's resumable, pretrained, or requires
219
+ specific file setup.
222
220
 
223
221
  Raises:
224
222
  ValueError: If the model is already trained, if required dataset information is missing, or if there are
@@ -247,17 +245,16 @@ class HUBTrainingSession:
247
245
  def request_queue(
248
246
  self,
249
247
  request_func,
250
- retry=3,
251
- timeout=30,
252
- thread=True,
253
- verbose=True,
254
- progress_total=None,
255
- stream_response=None,
248
+ retry: int = 3,
249
+ timeout: int = 30,
250
+ thread: bool = True,
251
+ verbose: bool = True,
252
+ progress_total: int | None = None,
253
+ stream_response: bool | None = None,
256
254
  *args,
257
255
  **kwargs,
258
256
  ):
259
- """
260
- Attempt to execute `request_func` with retries, timeout handling, optional threading, and progress tracking.
257
+ """Execute request_func with retries, timeout handling, optional threading, and progress tracking.
261
258
 
262
259
  Args:
263
260
  request_func (callable): The function to execute.
@@ -275,7 +272,7 @@ class HUBTrainingSession:
275
272
  """
276
273
 
277
274
  def retry_request():
278
- """Attempt to call `request_func` with retries, timeout, and optional threading."""
275
+ """Attempt to call request_func with retries, timeout, and optional threading."""
279
276
  t0 = time.time() # Record the start time for the timeout
280
277
  response = None
281
278
  for i in range(retry + 1):
@@ -327,16 +324,8 @@ class HUBTrainingSession:
327
324
  return retry_request()
328
325
 
329
326
  @staticmethod
330
- def _should_retry(status_code):
331
- """
332
- Determine if a request should be retried based on the HTTP status code.
333
-
334
- Args:
335
- status_code (int): The HTTP status code from the response.
336
-
337
- Returns:
338
- (bool): True if the request should be retried, False otherwise.
339
- """
327
+ def _should_retry(status_code: int) -> bool:
328
+ """Determine if a request should be retried based on the HTTP status code."""
340
329
  retry_codes = {
341
330
  HTTPStatus.REQUEST_TIMEOUT,
342
331
  HTTPStatus.BAD_GATEWAY,
@@ -344,9 +333,8 @@ class HUBTrainingSession:
344
333
  }
345
334
  return status_code in retry_codes
346
335
 
347
- def _get_failure_message(self, response: requests.Response, retry: int, timeout: int):
348
- """
349
- Generate a retry message based on the response status code.
336
+ def _get_failure_message(self, response, retry: int, timeout: int) -> str:
337
+ """Generate a retry message based on the response status code.
350
338
 
351
339
  Args:
352
340
  response (requests.Response): The HTTP response object.
@@ -382,8 +370,7 @@ class HUBTrainingSession:
382
370
  map: float = 0.0,
383
371
  final: bool = False,
384
372
  ) -> None:
385
- """
386
- Upload a model checkpoint to Ultralytics HUB.
373
+ """Upload a model checkpoint to Ultralytics HUB.
387
374
 
388
375
  Args:
389
376
  epoch (int): The current training epoch.
@@ -422,25 +409,14 @@ class HUBTrainingSession:
422
409
  )
423
410
 
424
411
  @staticmethod
425
- def _show_upload_progress(content_length: int, response: requests.Response) -> None:
426
- """
427
- Display a progress bar to track the upload progress of a file download.
428
-
429
- Args:
430
- content_length (int): The total size of the content to be downloaded in bytes.
431
- response (requests.Response): The response object from the file download request.
432
- """
412
+ def _show_upload_progress(content_length: int, response) -> None:
413
+ """Display a progress bar to track the upload progress of a file download."""
433
414
  with TQDM(total=content_length, unit="B", unit_scale=True, unit_divisor=1024) as pbar:
434
415
  for data in response.iter_content(chunk_size=1024):
435
416
  pbar.update(len(data))
436
417
 
437
418
  @staticmethod
438
- def _iterate_content(response: requests.Response) -> None:
439
- """
440
- Process the streamed HTTP response data.
441
-
442
- Args:
443
- response (requests.Response): The response object from the file download request.
444
- """
419
+ def _iterate_content(response) -> None:
420
+ """Process the streamed HTTP response data."""
445
421
  for _ in response.iter_content(chunk_size=1024):
446
422
  pass # Do nothing with data chunks
ultralytics/hub/utils.py CHANGED
@@ -1,32 +1,17 @@
1
1
  # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
2
 
3
3
  import os
4
- import platform
5
- import random
6
4
  import threading
7
5
  import time
8
- from pathlib import Path
6
+ from typing import Any
9
7
 
10
- import requests
11
-
12
- from ultralytics import __version__
13
8
  from ultralytics.utils import (
14
- ARGV,
15
- ENVIRONMENT,
16
9
  IS_COLAB,
17
- IS_GIT_DIR,
18
- IS_PIP_PACKAGE,
19
10
  LOGGER,
20
- ONLINE,
21
- RANK,
22
- SETTINGS,
23
- TESTS_RUNNING,
24
11
  TQDM,
25
12
  TryExcept,
26
13
  colorstr,
27
- get_git_origin_url,
28
14
  )
29
- from ultralytics.utils.downloads import GITHUB_ASSETS_NAMES
30
15
 
31
16
  HUB_API_ROOT = os.environ.get("ULTRALYTICS_HUB_API", "https://api.ultralytics.com")
32
17
  HUB_WEB_ROOT = os.environ.get("ULTRALYTICS_HUB_WEB", "https://hub.ultralytics.com")
@@ -35,9 +20,8 @@ PREFIX = colorstr("Ultralytics HUB: ")
35
20
  HELP_MSG = "If this issue persists please visit https://github.com/ultralytics/hub/issues for assistance."
36
21
 
37
22
 
38
- def request_with_credentials(url: str) -> any:
39
- """
40
- Make an AJAX request with cookies attached in a Google Colab environment.
23
+ def request_with_credentials(url: str) -> Any:
24
+ """Make an AJAX request with cookies attached in a Google Colab environment.
41
25
 
42
26
  Args:
43
27
  url (str): The URL to make the request to.
@@ -50,8 +34,8 @@ def request_with_credentials(url: str) -> any:
50
34
  """
51
35
  if not IS_COLAB:
52
36
  raise OSError("request_with_credentials() must run in a Colab environment")
53
- from google.colab import output # noqa
54
- from IPython import display # noqa
37
+ from google.colab import output
38
+ from IPython import display
55
39
 
56
40
  display.display(
57
41
  display.Javascript(
@@ -76,9 +60,8 @@ def request_with_credentials(url: str) -> any:
76
60
  return output.eval_js("_hub_tmp")
77
61
 
78
62
 
79
- def requests_with_progress(method, url, **kwargs):
80
- """
81
- Make an HTTP request using the specified method and URL, with an optional progress bar.
63
+ def requests_with_progress(method: str, url: str, **kwargs):
64
+ """Make an HTTP request using the specified method and URL, with an optional progress bar.
82
65
 
83
66
  Args:
84
67
  method (str): The HTTP method to use (e.g. 'GET', 'POST').
@@ -93,6 +76,8 @@ def requests_with_progress(method, url, **kwargs):
93
76
  content length.
94
77
  - If 'progress' is a number then progress bar will display assuming content length = progress.
95
78
  """
79
+ import requests # scoped as slow import
80
+
96
81
  progress = kwargs.pop("progress", False)
97
82
  if not progress:
98
83
  return requests.request(method, url, **kwargs)
@@ -108,9 +93,18 @@ def requests_with_progress(method, url, **kwargs):
108
93
  return response
109
94
 
110
95
 
111
- def smart_request(method, url, retry=3, timeout=30, thread=True, code=-1, verbose=True, progress=False, **kwargs):
112
- """
113
- Make an HTTP request using the 'requests' library, with exponential backoff retries up to a specified timeout.
96
+ def smart_request(
97
+ method: str,
98
+ url: str,
99
+ retry: int = 3,
100
+ timeout: int = 30,
101
+ thread: bool = True,
102
+ code: int = -1,
103
+ verbose: bool = True,
104
+ progress: bool = False,
105
+ **kwargs,
106
+ ):
107
+ """Make an HTTP request using the 'requests' library, with exponential backoff retries up to a specified timeout.
114
108
 
115
109
  Args:
116
110
  method (str): The HTTP method to use for the request. Choices are 'post' and 'get'.
@@ -124,7 +118,8 @@ def smart_request(method, url, retry=3, timeout=30, thread=True, code=-1, verbos
124
118
  **kwargs (Any): Keyword arguments to be passed to the requests function specified in method.
125
119
 
126
120
  Returns:
127
- (requests.Response): The HTTP response object. If the request is executed in a separate thread, returns None.
121
+ (requests.Response | None): The HTTP response object. If the request is executed in a separate thread, returns
122
+ None.
128
123
  """
129
124
  retry_codes = (408, 500) # retry only these codes
130
125
 
@@ -165,84 +160,3 @@ def smart_request(method, url, retry=3, timeout=30, thread=True, code=-1, verbos
165
160
  threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True).start()
166
161
  else:
167
162
  return func(*args, **kwargs)
168
-
169
-
170
- class Events:
171
- """
172
- A class for collecting anonymous event analytics.
173
-
174
- Event analytics are enabled when sync=True in settings and disabled when sync=False. Run 'yolo settings' to see and
175
- update settings.
176
-
177
- Attributes:
178
- url (str): The URL to send anonymous events.
179
- rate_limit (float): The rate limit in seconds for sending events.
180
- metadata (dict): A dictionary containing metadata about the environment.
181
- enabled (bool): A flag to enable or disable Events based on certain conditions.
182
- """
183
-
184
- url = "https://www.google-analytics.com/mp/collect?measurement_id=G-X8NCJYTQXM&api_secret=QLQrATrNSwGRFRLE-cbHJw"
185
-
186
- def __init__(self):
187
- """Initialize the Events object with default values for events, rate_limit, and metadata."""
188
- self.events = [] # events list
189
- self.rate_limit = 30.0 # rate limit (seconds)
190
- self.t = 0.0 # rate limit timer (seconds)
191
- self.metadata = {
192
- "cli": Path(ARGV[0]).name == "yolo",
193
- "install": "git" if IS_GIT_DIR else "pip" if IS_PIP_PACKAGE else "other",
194
- "python": ".".join(platform.python_version_tuple()[:2]), # i.e. 3.10
195
- "version": __version__,
196
- "env": ENVIRONMENT,
197
- "session_id": round(random.random() * 1e15),
198
- "engagement_time_msec": 1000,
199
- }
200
- self.enabled = (
201
- SETTINGS["sync"]
202
- and RANK in {-1, 0}
203
- and not TESTS_RUNNING
204
- and ONLINE
205
- and (IS_PIP_PACKAGE or get_git_origin_url() == "https://github.com/ultralytics/ultralytics.git")
206
- )
207
-
208
- def __call__(self, cfg):
209
- """
210
- Attempt to add a new event to the events list and send events if the rate limit is reached.
211
-
212
- Args:
213
- cfg (IterableSimpleNamespace): The configuration object containing mode and task information.
214
- """
215
- if not self.enabled:
216
- # Events disabled, do nothing
217
- return
218
-
219
- # Attempt to add to events
220
- if len(self.events) < 25: # Events list limited to 25 events (drop any events past this)
221
- params = {
222
- **self.metadata,
223
- "task": cfg.task,
224
- "model": cfg.model if cfg.model in GITHUB_ASSETS_NAMES else "custom",
225
- }
226
- if cfg.mode == "export":
227
- params["format"] = cfg.format
228
- self.events.append({"name": cfg.mode, "params": params})
229
-
230
- # Check rate limit
231
- t = time.time()
232
- if (t - self.t) < self.rate_limit:
233
- # Time is under rate limiter, wait to send
234
- return
235
-
236
- # Time is over rate limiter, send now
237
- data = {"client_id": SETTINGS["uuid"], "events": self.events} # SHA-256 anonymized UUID hash and events list
238
-
239
- # POST equivalent to requests.post(self.url, json=data)
240
- smart_request("post", self.url, json=data, retry=0, verbose=False)
241
-
242
- # Reset events and rate limit timer
243
- self.events = []
244
- self.t = t
245
-
246
-
247
- # Run below code on hub/utils init -------------------------------------------------------------------------------------
248
- events = Events()
@@ -6,4 +6,4 @@ from .rtdetr import RTDETR
6
6
  from .sam import SAM
7
7
  from .yolo import YOLO, YOLOE, YOLOWorld
8
8
 
9
- __all__ = "YOLO", "RTDETR", "SAM", "FastSAM", "NAS", "YOLOWorld", "YOLOE" # allow simpler import
9
+ __all__ = "NAS", "RTDETR", "SAM", "YOLO", "YOLOE", "FastSAM", "YOLOWorld" # allow simpler import
@@ -4,4 +4,4 @@ from .model import FastSAM
4
4
  from .predict import FastSAMPredictor
5
5
  from .val import FastSAMValidator
6
6
 
7
- __all__ = "FastSAMPredictor", "FastSAM", "FastSAMValidator"
7
+ __all__ = "FastSAM", "FastSAMPredictor", "FastSAMValidator"
@@ -1,6 +1,9 @@
1
1
  # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
2
 
3
+ from __future__ import annotations
4
+
3
5
  from pathlib import Path
6
+ from typing import Any
4
7
 
5
8
  from ultralytics.engine.model import Model
6
9
 
@@ -9,44 +12,59 @@ from .val import FastSAMValidator
9
12
 
10
13
 
11
14
  class FastSAM(Model):
12
- """
13
- FastSAM model interface for segment anything tasks.
15
+ """FastSAM model interface for segment anything tasks.
14
16
 
15
- This class extends the base Model class to provide specific functionality for the FastSAM (Fast Segment Anything Model)
16
- implementation, allowing for efficient and accurate image segmentation.
17
+ This class extends the base Model class to provide specific functionality for the FastSAM (Fast Segment Anything
18
+ Model) implementation, allowing for efficient and accurate image segmentation with optional prompting support.
17
19
 
18
20
  Attributes:
19
21
  model (str): Path to the pre-trained FastSAM model file.
20
22
  task (str): The task type, set to "segment" for FastSAM models.
21
23
 
24
+ Methods:
25
+ predict: Perform segmentation prediction on image or video source with optional prompts.
26
+ task_map: Returns mapping of segment task to predictor and validator classes.
27
+
22
28
  Examples:
29
+ Initialize FastSAM model and run prediction
23
30
  >>> from ultralytics import FastSAM
24
- >>> model = FastSAM("last.pt")
31
+ >>> model = FastSAM("FastSAM-x.pt")
25
32
  >>> results = model.predict("ultralytics/assets/bus.jpg")
33
+
34
+ Run prediction with bounding box prompts
35
+ >>> results = model.predict("image.jpg", bboxes=[[100, 100, 200, 200]])
26
36
  """
27
37
 
28
- def __init__(self, model="FastSAM-x.pt"):
38
+ def __init__(self, model: str = "FastSAM-x.pt"):
29
39
  """Initialize the FastSAM model with the specified pre-trained weights."""
30
40
  if str(model) == "FastSAM.pt":
31
41
  model = "FastSAM-x.pt"
32
42
  assert Path(model).suffix not in {".yaml", ".yml"}, "FastSAM models only support pre-trained models."
33
43
  super().__init__(model=model, task="segment")
34
44
 
35
- def predict(self, source, stream=False, bboxes=None, points=None, labels=None, texts=None, **kwargs):
36
- """
37
- Perform segmentation prediction on image or video source.
45
+ def predict(
46
+ self,
47
+ source,
48
+ stream: bool = False,
49
+ bboxes: list | None = None,
50
+ points: list | None = None,
51
+ labels: list | None = None,
52
+ texts: list | None = None,
53
+ **kwargs: Any,
54
+ ):
55
+ """Perform segmentation prediction on image or video source.
38
56
 
39
- Supports prompted segmentation with bounding boxes, points, labels, and texts. The method packages these
40
- prompts and passes them to the parent class predict method.
57
+ Supports prompted segmentation with bounding boxes, points, labels, and texts. The method packages these prompts
58
+ and passes them to the parent class predict method for processing.
41
59
 
42
60
  Args:
43
- source (str | PIL.Image | numpy.ndarray): Input source for prediction, can be a file path, URL, PIL image,
44
- or numpy array.
61
+ source (str | PIL.Image | np.ndarray): Input source for prediction, can be a file path, URL, PIL image, or
62
+ numpy array.
45
63
  stream (bool): Whether to enable real-time streaming mode for video inputs.
46
- bboxes (list): Bounding box coordinates for prompted segmentation in format [[x1, y1, x2, y2], ...].
47
- points (list): Point coordinates for prompted segmentation in format [[x, y], ...].
48
- labels (list): Class labels for prompted segmentation.
49
- texts (list): Text prompts for segmentation guidance.
64
+ bboxes (list, optional): Bounding box coordinates for prompted segmentation in format [[x1, y1, x2, y2]].
65
+ points (list, optional): Point coordinates for prompted segmentation in format [[x, y]].
66
+ labels (list, optional): Class labels for prompted segmentation.
67
+ texts (list, optional): Text prompts for segmentation guidance.
50
68
  **kwargs (Any): Additional keyword arguments passed to the predictor.
51
69
 
52
70
  Returns:
@@ -56,6 +74,6 @@ class FastSAM(Model):
56
74
  return super().predict(source, stream, prompts=prompts, **kwargs)
57
75
 
58
76
  @property
59
- def task_map(self):
77
+ def task_map(self) -> dict[str, dict[str, Any]]:
60
78
  """Returns a dictionary mapping segment task to corresponding predictor and validator classes."""
61
79
  return {"segment": {"predictor": FastSAMPredictor, "validator": FastSAMValidator}}