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