ultralytics-opencv-headless 8.3.246__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tests/__init__.py +23 -0
- tests/conftest.py +59 -0
- tests/test_cli.py +131 -0
- tests/test_cuda.py +216 -0
- tests/test_engine.py +157 -0
- tests/test_exports.py +309 -0
- tests/test_integrations.py +151 -0
- tests/test_python.py +777 -0
- tests/test_solutions.py +371 -0
- ultralytics/__init__.py +48 -0
- ultralytics/assets/bus.jpg +0 -0
- ultralytics/assets/zidane.jpg +0 -0
- ultralytics/cfg/__init__.py +1026 -0
- ultralytics/cfg/datasets/Argoverse.yaml +78 -0
- ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
- ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
- ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
- ultralytics/cfg/datasets/HomeObjects-3K.yaml +32 -0
- ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
- ultralytics/cfg/datasets/Objects365.yaml +447 -0
- ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
- ultralytics/cfg/datasets/VOC.yaml +102 -0
- ultralytics/cfg/datasets/VisDrone.yaml +87 -0
- ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
- ultralytics/cfg/datasets/brain-tumor.yaml +22 -0
- ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
- ultralytics/cfg/datasets/coco-pose.yaml +64 -0
- ultralytics/cfg/datasets/coco.yaml +118 -0
- ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
- ultralytics/cfg/datasets/coco128.yaml +101 -0
- ultralytics/cfg/datasets/coco8-grayscale.yaml +103 -0
- ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
- ultralytics/cfg/datasets/coco8-pose.yaml +47 -0
- ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
- ultralytics/cfg/datasets/coco8.yaml +101 -0
- ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
- ultralytics/cfg/datasets/crack-seg.yaml +22 -0
- ultralytics/cfg/datasets/dog-pose.yaml +52 -0
- ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
- ultralytics/cfg/datasets/dota8.yaml +35 -0
- ultralytics/cfg/datasets/hand-keypoints.yaml +50 -0
- ultralytics/cfg/datasets/kitti.yaml +27 -0
- ultralytics/cfg/datasets/lvis.yaml +1240 -0
- ultralytics/cfg/datasets/medical-pills.yaml +21 -0
- ultralytics/cfg/datasets/open-images-v7.yaml +663 -0
- ultralytics/cfg/datasets/package-seg.yaml +22 -0
- ultralytics/cfg/datasets/signature.yaml +21 -0
- ultralytics/cfg/datasets/tiger-pose.yaml +41 -0
- ultralytics/cfg/datasets/xView.yaml +155 -0
- ultralytics/cfg/default.yaml +130 -0
- ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
- ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
- ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
- ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
- ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
- ultralytics/cfg/models/11/yolo11.yaml +50 -0
- ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
- ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
- ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
- ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
- ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
- ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
- ultralytics/cfg/models/12/yolo12.yaml +48 -0
- ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
- ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
- ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
- ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
- ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
- ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
- ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
- ultralytics/cfg/models/v3/yolov3.yaml +49 -0
- ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
- ultralytics/cfg/models/v5/yolov5.yaml +51 -0
- ultralytics/cfg/models/v6/yolov6.yaml +56 -0
- ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +48 -0
- ultralytics/cfg/models/v8/yoloe-v8.yaml +48 -0
- ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
- ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
- ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
- ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
- ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
- ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
- ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
- ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
- ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
- ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
- ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
- ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
- ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8.yaml +49 -0
- ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
- ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
- ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
- ultralytics/cfg/trackers/botsort.yaml +21 -0
- ultralytics/cfg/trackers/bytetrack.yaml +12 -0
- ultralytics/data/__init__.py +26 -0
- ultralytics/data/annotator.py +66 -0
- ultralytics/data/augment.py +2801 -0
- ultralytics/data/base.py +435 -0
- ultralytics/data/build.py +437 -0
- ultralytics/data/converter.py +855 -0
- ultralytics/data/dataset.py +834 -0
- ultralytics/data/loaders.py +704 -0
- ultralytics/data/scripts/download_weights.sh +18 -0
- ultralytics/data/scripts/get_coco.sh +61 -0
- ultralytics/data/scripts/get_coco128.sh +18 -0
- ultralytics/data/scripts/get_imagenet.sh +52 -0
- ultralytics/data/split.py +138 -0
- ultralytics/data/split_dota.py +344 -0
- ultralytics/data/utils.py +798 -0
- ultralytics/engine/__init__.py +1 -0
- ultralytics/engine/exporter.py +1578 -0
- ultralytics/engine/model.py +1124 -0
- ultralytics/engine/predictor.py +508 -0
- ultralytics/engine/results.py +1522 -0
- ultralytics/engine/trainer.py +974 -0
- ultralytics/engine/tuner.py +448 -0
- ultralytics/engine/validator.py +384 -0
- ultralytics/hub/__init__.py +166 -0
- ultralytics/hub/auth.py +151 -0
- ultralytics/hub/google/__init__.py +174 -0
- ultralytics/hub/session.py +422 -0
- ultralytics/hub/utils.py +162 -0
- ultralytics/models/__init__.py +9 -0
- ultralytics/models/fastsam/__init__.py +7 -0
- ultralytics/models/fastsam/model.py +79 -0
- ultralytics/models/fastsam/predict.py +169 -0
- ultralytics/models/fastsam/utils.py +23 -0
- ultralytics/models/fastsam/val.py +38 -0
- ultralytics/models/nas/__init__.py +7 -0
- ultralytics/models/nas/model.py +98 -0
- ultralytics/models/nas/predict.py +56 -0
- ultralytics/models/nas/val.py +38 -0
- ultralytics/models/rtdetr/__init__.py +7 -0
- ultralytics/models/rtdetr/model.py +63 -0
- ultralytics/models/rtdetr/predict.py +88 -0
- ultralytics/models/rtdetr/train.py +89 -0
- ultralytics/models/rtdetr/val.py +216 -0
- ultralytics/models/sam/__init__.py +25 -0
- ultralytics/models/sam/amg.py +275 -0
- ultralytics/models/sam/build.py +365 -0
- ultralytics/models/sam/build_sam3.py +377 -0
- ultralytics/models/sam/model.py +169 -0
- ultralytics/models/sam/modules/__init__.py +1 -0
- ultralytics/models/sam/modules/blocks.py +1067 -0
- ultralytics/models/sam/modules/decoders.py +495 -0
- ultralytics/models/sam/modules/encoders.py +794 -0
- ultralytics/models/sam/modules/memory_attention.py +298 -0
- ultralytics/models/sam/modules/sam.py +1160 -0
- ultralytics/models/sam/modules/tiny_encoder.py +979 -0
- ultralytics/models/sam/modules/transformer.py +344 -0
- ultralytics/models/sam/modules/utils.py +512 -0
- ultralytics/models/sam/predict.py +3940 -0
- ultralytics/models/sam/sam3/__init__.py +3 -0
- ultralytics/models/sam/sam3/decoder.py +546 -0
- ultralytics/models/sam/sam3/encoder.py +529 -0
- ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
- ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
- ultralytics/models/sam/sam3/model_misc.py +199 -0
- ultralytics/models/sam/sam3/necks.py +129 -0
- ultralytics/models/sam/sam3/sam3_image.py +339 -0
- ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
- ultralytics/models/sam/sam3/vitdet.py +547 -0
- ultralytics/models/sam/sam3/vl_combiner.py +160 -0
- ultralytics/models/utils/__init__.py +1 -0
- ultralytics/models/utils/loss.py +466 -0
- ultralytics/models/utils/ops.py +315 -0
- ultralytics/models/yolo/__init__.py +7 -0
- ultralytics/models/yolo/classify/__init__.py +7 -0
- ultralytics/models/yolo/classify/predict.py +90 -0
- ultralytics/models/yolo/classify/train.py +202 -0
- ultralytics/models/yolo/classify/val.py +216 -0
- ultralytics/models/yolo/detect/__init__.py +7 -0
- ultralytics/models/yolo/detect/predict.py +122 -0
- ultralytics/models/yolo/detect/train.py +227 -0
- ultralytics/models/yolo/detect/val.py +507 -0
- ultralytics/models/yolo/model.py +430 -0
- ultralytics/models/yolo/obb/__init__.py +7 -0
- ultralytics/models/yolo/obb/predict.py +56 -0
- ultralytics/models/yolo/obb/train.py +79 -0
- ultralytics/models/yolo/obb/val.py +302 -0
- ultralytics/models/yolo/pose/__init__.py +7 -0
- ultralytics/models/yolo/pose/predict.py +65 -0
- ultralytics/models/yolo/pose/train.py +110 -0
- ultralytics/models/yolo/pose/val.py +248 -0
- ultralytics/models/yolo/segment/__init__.py +7 -0
- ultralytics/models/yolo/segment/predict.py +109 -0
- ultralytics/models/yolo/segment/train.py +69 -0
- ultralytics/models/yolo/segment/val.py +307 -0
- ultralytics/models/yolo/world/__init__.py +5 -0
- ultralytics/models/yolo/world/train.py +173 -0
- ultralytics/models/yolo/world/train_world.py +178 -0
- ultralytics/models/yolo/yoloe/__init__.py +22 -0
- ultralytics/models/yolo/yoloe/predict.py +162 -0
- ultralytics/models/yolo/yoloe/train.py +287 -0
- ultralytics/models/yolo/yoloe/train_seg.py +122 -0
- ultralytics/models/yolo/yoloe/val.py +206 -0
- ultralytics/nn/__init__.py +27 -0
- ultralytics/nn/autobackend.py +958 -0
- ultralytics/nn/modules/__init__.py +182 -0
- ultralytics/nn/modules/activation.py +54 -0
- ultralytics/nn/modules/block.py +1947 -0
- ultralytics/nn/modules/conv.py +669 -0
- ultralytics/nn/modules/head.py +1183 -0
- ultralytics/nn/modules/transformer.py +793 -0
- ultralytics/nn/modules/utils.py +159 -0
- ultralytics/nn/tasks.py +1768 -0
- ultralytics/nn/text_model.py +356 -0
- ultralytics/py.typed +1 -0
- ultralytics/solutions/__init__.py +41 -0
- ultralytics/solutions/ai_gym.py +108 -0
- ultralytics/solutions/analytics.py +264 -0
- ultralytics/solutions/config.py +107 -0
- ultralytics/solutions/distance_calculation.py +123 -0
- ultralytics/solutions/heatmap.py +125 -0
- ultralytics/solutions/instance_segmentation.py +86 -0
- ultralytics/solutions/object_blurrer.py +89 -0
- ultralytics/solutions/object_counter.py +190 -0
- ultralytics/solutions/object_cropper.py +87 -0
- ultralytics/solutions/parking_management.py +280 -0
- ultralytics/solutions/queue_management.py +93 -0
- ultralytics/solutions/region_counter.py +133 -0
- ultralytics/solutions/security_alarm.py +151 -0
- ultralytics/solutions/similarity_search.py +219 -0
- ultralytics/solutions/solutions.py +828 -0
- ultralytics/solutions/speed_estimation.py +114 -0
- ultralytics/solutions/streamlit_inference.py +260 -0
- ultralytics/solutions/templates/similarity-search.html +156 -0
- ultralytics/solutions/trackzone.py +88 -0
- ultralytics/solutions/vision_eye.py +67 -0
- ultralytics/trackers/__init__.py +7 -0
- ultralytics/trackers/basetrack.py +115 -0
- ultralytics/trackers/bot_sort.py +257 -0
- ultralytics/trackers/byte_tracker.py +469 -0
- ultralytics/trackers/track.py +116 -0
- ultralytics/trackers/utils/__init__.py +1 -0
- ultralytics/trackers/utils/gmc.py +339 -0
- ultralytics/trackers/utils/kalman_filter.py +482 -0
- ultralytics/trackers/utils/matching.py +154 -0
- ultralytics/utils/__init__.py +1450 -0
- ultralytics/utils/autobatch.py +118 -0
- ultralytics/utils/autodevice.py +205 -0
- ultralytics/utils/benchmarks.py +728 -0
- ultralytics/utils/callbacks/__init__.py +5 -0
- ultralytics/utils/callbacks/base.py +233 -0
- ultralytics/utils/callbacks/clearml.py +146 -0
- ultralytics/utils/callbacks/comet.py +625 -0
- ultralytics/utils/callbacks/dvc.py +197 -0
- ultralytics/utils/callbacks/hub.py +110 -0
- ultralytics/utils/callbacks/mlflow.py +134 -0
- ultralytics/utils/callbacks/neptune.py +126 -0
- ultralytics/utils/callbacks/platform.py +313 -0
- ultralytics/utils/callbacks/raytune.py +42 -0
- ultralytics/utils/callbacks/tensorboard.py +123 -0
- ultralytics/utils/callbacks/wb.py +188 -0
- ultralytics/utils/checks.py +1006 -0
- ultralytics/utils/cpu.py +85 -0
- ultralytics/utils/dist.py +123 -0
- ultralytics/utils/downloads.py +529 -0
- ultralytics/utils/errors.py +35 -0
- ultralytics/utils/events.py +113 -0
- ultralytics/utils/export/__init__.py +7 -0
- ultralytics/utils/export/engine.py +237 -0
- ultralytics/utils/export/imx.py +315 -0
- ultralytics/utils/export/tensorflow.py +231 -0
- ultralytics/utils/files.py +219 -0
- ultralytics/utils/git.py +137 -0
- ultralytics/utils/instance.py +484 -0
- ultralytics/utils/logger.py +501 -0
- ultralytics/utils/loss.py +849 -0
- ultralytics/utils/metrics.py +1563 -0
- ultralytics/utils/nms.py +337 -0
- ultralytics/utils/ops.py +664 -0
- ultralytics/utils/patches.py +201 -0
- ultralytics/utils/plotting.py +1045 -0
- ultralytics/utils/tal.py +403 -0
- ultralytics/utils/torch_utils.py +984 -0
- ultralytics/utils/tqdm.py +440 -0
- ultralytics/utils/triton.py +112 -0
- ultralytics/utils/tuner.py +160 -0
- ultralytics_opencv_headless-8.3.246.dist-info/METADATA +374 -0
- ultralytics_opencv_headless-8.3.246.dist-info/RECORD +298 -0
- ultralytics_opencv_headless-8.3.246.dist-info/WHEEL +5 -0
- ultralytics_opencv_headless-8.3.246.dist-info/entry_points.txt +3 -0
- ultralytics_opencv_headless-8.3.246.dist-info/licenses/LICENSE +661 -0
- ultralytics_opencv_headless-8.3.246.dist-info/top_level.txt +1 -0
ultralytics/hub/auth.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
|
2
|
+
|
|
3
|
+
from ultralytics.hub.utils import HUB_API_ROOT, HUB_WEB_ROOT, PREFIX, request_with_credentials
|
|
4
|
+
from ultralytics.utils import IS_COLAB, LOGGER, SETTINGS, emojis
|
|
5
|
+
|
|
6
|
+
API_KEY_URL = f"{HUB_WEB_ROOT}/settings?tab=api+keys"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Auth:
|
|
10
|
+
"""Manages authentication processes including API key handling, cookie-based authentication, and header generation.
|
|
11
|
+
|
|
12
|
+
The class supports different methods of authentication:
|
|
13
|
+
1. Directly using an API key.
|
|
14
|
+
2. Authenticating using browser cookies (specifically in Google Colab).
|
|
15
|
+
3. Prompting the user to enter an API key.
|
|
16
|
+
|
|
17
|
+
Attributes:
|
|
18
|
+
id_token (str | bool): Token used for identity verification, initialized as False.
|
|
19
|
+
api_key (str | bool): API key for authentication, initialized as False.
|
|
20
|
+
model_key (bool): Placeholder for model key, initialized as False.
|
|
21
|
+
|
|
22
|
+
Methods:
|
|
23
|
+
authenticate: Attempt to authenticate with the server using either id_token or API key.
|
|
24
|
+
auth_with_cookies: Attempt to fetch authentication via cookies and set id_token.
|
|
25
|
+
get_auth_header: Get the authentication header for making API requests.
|
|
26
|
+
request_api_key: Prompt the user to input their API key.
|
|
27
|
+
|
|
28
|
+
Examples:
|
|
29
|
+
Initialize Auth with an API key
|
|
30
|
+
>>> auth = Auth(api_key="your_api_key_here")
|
|
31
|
+
|
|
32
|
+
Initialize Auth without API key (will prompt for input)
|
|
33
|
+
>>> auth = Auth()
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
id_token = api_key = model_key = False
|
|
37
|
+
|
|
38
|
+
def __init__(self, api_key: str = "", verbose: bool = False):
|
|
39
|
+
"""Initialize Auth class and authenticate user.
|
|
40
|
+
|
|
41
|
+
Handles API key validation, Google Colab authentication, and new key requests. Updates SETTINGS upon successful
|
|
42
|
+
authentication.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
api_key (str): API key or combined key_id format.
|
|
46
|
+
verbose (bool): Enable verbose logging.
|
|
47
|
+
"""
|
|
48
|
+
# Split the input API key in case it contains a combined key_model and keep only the API key part
|
|
49
|
+
api_key = api_key.split("_", 1)[0]
|
|
50
|
+
|
|
51
|
+
# Set API key attribute as value passed or SETTINGS API key if none passed
|
|
52
|
+
self.api_key = api_key or SETTINGS.get("api_key", "")
|
|
53
|
+
|
|
54
|
+
# If an API key is provided
|
|
55
|
+
if self.api_key:
|
|
56
|
+
# If the provided API key matches the API key in the SETTINGS
|
|
57
|
+
if self.api_key == SETTINGS.get("api_key"):
|
|
58
|
+
# Log that the user is already logged in
|
|
59
|
+
if verbose:
|
|
60
|
+
LOGGER.info(f"{PREFIX}Authenticated ✅")
|
|
61
|
+
return
|
|
62
|
+
else:
|
|
63
|
+
# Attempt to authenticate with the provided API key
|
|
64
|
+
success = self.authenticate()
|
|
65
|
+
# If the API key is not provided and the environment is a Google Colab notebook
|
|
66
|
+
elif IS_COLAB:
|
|
67
|
+
# Attempt to authenticate using browser cookies
|
|
68
|
+
success = self.auth_with_cookies()
|
|
69
|
+
else:
|
|
70
|
+
# Request an API key
|
|
71
|
+
success = self.request_api_key()
|
|
72
|
+
|
|
73
|
+
# Update SETTINGS with the new API key after successful authentication
|
|
74
|
+
if success:
|
|
75
|
+
SETTINGS.update({"api_key": self.api_key})
|
|
76
|
+
# Log that the new login was successful
|
|
77
|
+
if verbose:
|
|
78
|
+
LOGGER.info(f"{PREFIX}New authentication successful ✅")
|
|
79
|
+
elif verbose:
|
|
80
|
+
LOGGER.info(f"{PREFIX}Get API key from {API_KEY_URL} and then run 'yolo login API_KEY'")
|
|
81
|
+
|
|
82
|
+
def request_api_key(self, max_attempts: int = 3) -> bool:
|
|
83
|
+
"""Prompt the user to input their API key.
|
|
84
|
+
|
|
85
|
+
Args:
|
|
86
|
+
max_attempts (int): Maximum number of authentication attempts.
|
|
87
|
+
|
|
88
|
+
Returns:
|
|
89
|
+
(bool): True if authentication is successful, False otherwise.
|
|
90
|
+
"""
|
|
91
|
+
import getpass
|
|
92
|
+
|
|
93
|
+
for attempts in range(max_attempts):
|
|
94
|
+
LOGGER.info(f"{PREFIX}Login. Attempt {attempts + 1} of {max_attempts}")
|
|
95
|
+
input_key = getpass.getpass(f"Enter API key from {API_KEY_URL} ")
|
|
96
|
+
self.api_key = input_key.split("_", 1)[0] # remove model id if present
|
|
97
|
+
if self.authenticate():
|
|
98
|
+
return True
|
|
99
|
+
raise ConnectionError(emojis(f"{PREFIX}Failed to authenticate ❌"))
|
|
100
|
+
|
|
101
|
+
def authenticate(self) -> bool:
|
|
102
|
+
"""Attempt to authenticate with the server using either id_token or API key.
|
|
103
|
+
|
|
104
|
+
Returns:
|
|
105
|
+
(bool): True if authentication is successful, False otherwise.
|
|
106
|
+
"""
|
|
107
|
+
import requests # scoped as slow import
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
if header := self.get_auth_header():
|
|
111
|
+
r = requests.post(f"{HUB_API_ROOT}/v1/auth", headers=header)
|
|
112
|
+
if not r.json().get("success", False):
|
|
113
|
+
raise ConnectionError("Unable to authenticate.")
|
|
114
|
+
return True
|
|
115
|
+
raise ConnectionError("User has not authenticated locally.")
|
|
116
|
+
except ConnectionError:
|
|
117
|
+
self.id_token = self.api_key = False # reset invalid
|
|
118
|
+
LOGGER.warning(f"{PREFIX}Invalid API key")
|
|
119
|
+
return False
|
|
120
|
+
|
|
121
|
+
def auth_with_cookies(self) -> bool:
|
|
122
|
+
"""Attempt to fetch authentication via cookies and set id_token.
|
|
123
|
+
|
|
124
|
+
User must be logged in to HUB and running in a supported browser.
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
(bool): True if authentication is successful, False otherwise.
|
|
128
|
+
"""
|
|
129
|
+
if not IS_COLAB:
|
|
130
|
+
return False # Currently only works with Colab
|
|
131
|
+
try:
|
|
132
|
+
authn = request_with_credentials(f"{HUB_API_ROOT}/v1/auth/auto")
|
|
133
|
+
if authn.get("success", False):
|
|
134
|
+
self.id_token = authn.get("data", {}).get("idToken", None)
|
|
135
|
+
self.authenticate()
|
|
136
|
+
return True
|
|
137
|
+
raise ConnectionError("Unable to fetch browser authentication details.")
|
|
138
|
+
except ConnectionError:
|
|
139
|
+
self.id_token = False # reset invalid
|
|
140
|
+
return False
|
|
141
|
+
|
|
142
|
+
def get_auth_header(self):
|
|
143
|
+
"""Get the authentication header for making API requests.
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
(dict | None): The authentication header if id_token or API key is set, None otherwise.
|
|
147
|
+
"""
|
|
148
|
+
if self.id_token:
|
|
149
|
+
return {"authorization": f"Bearer {self.id_token}"}
|
|
150
|
+
elif self.api_key:
|
|
151
|
+
return {"x-api-key": self.api_key}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import concurrent.futures
|
|
6
|
+
import statistics
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class GCPRegions:
|
|
11
|
+
"""A class for managing and analyzing Google Cloud Platform (GCP) regions.
|
|
12
|
+
|
|
13
|
+
This class provides functionality to initialize, categorize, and analyze GCP regions based on their geographical
|
|
14
|
+
location, tier classification, and network latency.
|
|
15
|
+
|
|
16
|
+
Attributes:
|
|
17
|
+
regions (dict[str, tuple[int, str, str]]): A dictionary of GCP regions with their tier, city, and country.
|
|
18
|
+
|
|
19
|
+
Methods:
|
|
20
|
+
tier1: Returns a list of tier 1 GCP regions.
|
|
21
|
+
tier2: Returns a list of tier 2 GCP regions.
|
|
22
|
+
lowest_latency: Determines the GCP region(s) with the lowest network latency.
|
|
23
|
+
|
|
24
|
+
Examples:
|
|
25
|
+
>>> from ultralytics.hub.google import GCPRegions
|
|
26
|
+
>>> regions = GCPRegions()
|
|
27
|
+
>>> lowest_latency_region = regions.lowest_latency(verbose=True, attempts=3)
|
|
28
|
+
>>> print(f"Lowest latency region: {lowest_latency_region[0][0]}")
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
def __init__(self):
|
|
32
|
+
"""Initialize the GCPRegions class with predefined Google Cloud Platform regions and their details."""
|
|
33
|
+
self.regions = {
|
|
34
|
+
"asia-east1": (1, "Taiwan", "China"),
|
|
35
|
+
"asia-east2": (2, "Hong Kong", "China"),
|
|
36
|
+
"asia-northeast1": (1, "Tokyo", "Japan"),
|
|
37
|
+
"asia-northeast2": (1, "Osaka", "Japan"),
|
|
38
|
+
"asia-northeast3": (2, "Seoul", "South Korea"),
|
|
39
|
+
"asia-south1": (2, "Mumbai", "India"),
|
|
40
|
+
"asia-south2": (2, "Delhi", "India"),
|
|
41
|
+
"asia-southeast1": (2, "Jurong West", "Singapore"),
|
|
42
|
+
"asia-southeast2": (2, "Jakarta", "Indonesia"),
|
|
43
|
+
"australia-southeast1": (2, "Sydney", "Australia"),
|
|
44
|
+
"australia-southeast2": (2, "Melbourne", "Australia"),
|
|
45
|
+
"europe-central2": (2, "Warsaw", "Poland"),
|
|
46
|
+
"europe-north1": (1, "Hamina", "Finland"),
|
|
47
|
+
"europe-southwest1": (1, "Madrid", "Spain"),
|
|
48
|
+
"europe-west1": (1, "St. Ghislain", "Belgium"),
|
|
49
|
+
"europe-west10": (2, "Berlin", "Germany"),
|
|
50
|
+
"europe-west12": (2, "Turin", "Italy"),
|
|
51
|
+
"europe-west2": (2, "London", "United Kingdom"),
|
|
52
|
+
"europe-west3": (2, "Frankfurt", "Germany"),
|
|
53
|
+
"europe-west4": (1, "Eemshaven", "Netherlands"),
|
|
54
|
+
"europe-west6": (2, "Zurich", "Switzerland"),
|
|
55
|
+
"europe-west8": (1, "Milan", "Italy"),
|
|
56
|
+
"europe-west9": (1, "Paris", "France"),
|
|
57
|
+
"me-central1": (2, "Doha", "Qatar"),
|
|
58
|
+
"me-west1": (1, "Tel Aviv", "Israel"),
|
|
59
|
+
"northamerica-northeast1": (2, "Montreal", "Canada"),
|
|
60
|
+
"northamerica-northeast2": (2, "Toronto", "Canada"),
|
|
61
|
+
"southamerica-east1": (2, "São Paulo", "Brazil"),
|
|
62
|
+
"southamerica-west1": (2, "Santiago", "Chile"),
|
|
63
|
+
"us-central1": (1, "Iowa", "United States"),
|
|
64
|
+
"us-east1": (1, "South Carolina", "United States"),
|
|
65
|
+
"us-east4": (1, "Northern Virginia", "United States"),
|
|
66
|
+
"us-east5": (1, "Columbus", "United States"),
|
|
67
|
+
"us-south1": (1, "Dallas", "United States"),
|
|
68
|
+
"us-west1": (1, "Oregon", "United States"),
|
|
69
|
+
"us-west2": (2, "Los Angeles", "United States"),
|
|
70
|
+
"us-west3": (2, "Salt Lake City", "United States"),
|
|
71
|
+
"us-west4": (2, "Las Vegas", "United States"),
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
def tier1(self) -> list[str]:
|
|
75
|
+
"""Return a list of GCP regions classified as tier 1 based on predefined criteria."""
|
|
76
|
+
return [region for region, info in self.regions.items() if info[0] == 1]
|
|
77
|
+
|
|
78
|
+
def tier2(self) -> list[str]:
|
|
79
|
+
"""Return a list of GCP regions classified as tier 2 based on predefined criteria."""
|
|
80
|
+
return [region for region, info in self.regions.items() if info[0] == 2]
|
|
81
|
+
|
|
82
|
+
@staticmethod
|
|
83
|
+
def _ping_region(region: str, attempts: int = 1) -> tuple[str, float, float, float, float]:
|
|
84
|
+
"""Ping a specified GCP region and measure network latency statistics.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
region (str): The GCP region identifier to ping (e.g., 'us-central1').
|
|
88
|
+
attempts (int, optional): Number of ping attempts to make for calculating statistics.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
region (str): The GCP region identifier that was pinged.
|
|
92
|
+
mean_latency (float): Mean latency in milliseconds, or infinity if all pings failed.
|
|
93
|
+
std_dev (float): Standard deviation of latencies in milliseconds, or infinity if all pings failed.
|
|
94
|
+
min_latency (float): Minimum latency in milliseconds, or infinity if all pings failed.
|
|
95
|
+
max_latency (float): Maximum latency in milliseconds, or infinity if all pings failed.
|
|
96
|
+
|
|
97
|
+
Examples:
|
|
98
|
+
>>> region, mean, std, min_lat, max_lat = GCPRegions._ping_region("us-central1", attempts=3)
|
|
99
|
+
>>> print(f"Region {region} has mean latency: {mean:.2f}ms")
|
|
100
|
+
"""
|
|
101
|
+
import requests # scoped as slow import
|
|
102
|
+
|
|
103
|
+
url = f"https://{region}-docker.pkg.dev"
|
|
104
|
+
latencies = []
|
|
105
|
+
for _ in range(attempts):
|
|
106
|
+
try:
|
|
107
|
+
start_time = time.time()
|
|
108
|
+
_ = requests.head(url, timeout=5)
|
|
109
|
+
latency = (time.time() - start_time) * 1000 # Convert latency to milliseconds
|
|
110
|
+
if latency != float("inf"):
|
|
111
|
+
latencies.append(latency)
|
|
112
|
+
except requests.RequestException:
|
|
113
|
+
pass
|
|
114
|
+
if not latencies:
|
|
115
|
+
return region, float("inf"), float("inf"), float("inf"), float("inf")
|
|
116
|
+
|
|
117
|
+
std_dev = statistics.stdev(latencies) if len(latencies) > 1 else 0
|
|
118
|
+
return region, statistics.mean(latencies), std_dev, min(latencies), max(latencies)
|
|
119
|
+
|
|
120
|
+
def lowest_latency(
|
|
121
|
+
self,
|
|
122
|
+
top: int = 1,
|
|
123
|
+
verbose: bool = False,
|
|
124
|
+
tier: int | None = None,
|
|
125
|
+
attempts: int = 1,
|
|
126
|
+
) -> list[tuple[str, float, float, float, float]]:
|
|
127
|
+
"""Determine the GCP regions with the lowest latency based on ping tests.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
top (int, optional): Number of top regions to return.
|
|
131
|
+
verbose (bool, optional): If True, prints detailed latency information for all tested regions.
|
|
132
|
+
tier (int | None, optional): Filter regions by tier (1 or 2). If None, all regions are tested.
|
|
133
|
+
attempts (int, optional): Number of ping attempts per region.
|
|
134
|
+
|
|
135
|
+
Returns:
|
|
136
|
+
(list[tuple[str, float, float, float, float]]): List of tuples containing region information and latency
|
|
137
|
+
statistics. Each tuple contains (region, mean_latency, std_dev, min_latency, max_latency).
|
|
138
|
+
|
|
139
|
+
Examples:
|
|
140
|
+
>>> regions = GCPRegions()
|
|
141
|
+
>>> results = regions.lowest_latency(top=3, verbose=True, tier=1, attempts=2)
|
|
142
|
+
>>> print(results[0][0]) # Print the name of the lowest latency region
|
|
143
|
+
"""
|
|
144
|
+
if verbose:
|
|
145
|
+
print(f"Testing GCP regions for latency (with {attempts} {'retry' if attempts == 1 else 'attempts'})...")
|
|
146
|
+
|
|
147
|
+
regions_to_test = [k for k, v in self.regions.items() if v[0] == tier] if tier else list(self.regions.keys())
|
|
148
|
+
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
|
|
149
|
+
results = list(executor.map(lambda r: self._ping_region(r, attempts), regions_to_test))
|
|
150
|
+
|
|
151
|
+
sorted_results = sorted(results, key=lambda x: x[1])
|
|
152
|
+
|
|
153
|
+
if verbose:
|
|
154
|
+
print(f"{'Region':<25} {'Location':<35} {'Tier':<5} Latency (ms)")
|
|
155
|
+
for region, mean, std, min_, max_ in sorted_results:
|
|
156
|
+
tier, city, country = self.regions[region]
|
|
157
|
+
location = f"{city}, {country}"
|
|
158
|
+
if mean == float("inf"):
|
|
159
|
+
print(f"{region:<25} {location:<35} {tier:<5} Timeout")
|
|
160
|
+
else:
|
|
161
|
+
print(f"{region:<25} {location:<35} {tier:<5} {mean:.0f} ± {std:.0f} ({min_:.0f} - {max_:.0f})")
|
|
162
|
+
print(f"\nLowest latency region{'s' if top > 1 else ''}:")
|
|
163
|
+
for region, mean, std, min_, max_ in sorted_results[:top]:
|
|
164
|
+
tier, city, country = self.regions[region]
|
|
165
|
+
location = f"{city}, {country}"
|
|
166
|
+
print(f"{region} ({location}, {mean:.0f} ± {std:.0f} ms ({min_:.0f} - {max_:.0f}))")
|
|
167
|
+
|
|
168
|
+
return sorted_results[:top]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
# Usage example
|
|
172
|
+
if __name__ == "__main__":
|
|
173
|
+
regions = GCPRegions()
|
|
174
|
+
top_3_latency_tier1 = regions.lowest_latency(top=3, verbose=True, tier=1, attempts=3)
|