mirror of
https://github.com/ultralytics/yolov5.git
synced 2025-06-03 14:49:29 +08:00
* Add license line to .github/ISSUE_TEMPLATE/bug-report.yml * Add license line to .github/ISSUE_TEMPLATE/config.yml * Add license line to .github/ISSUE_TEMPLATE/feature-request.yml * Add license line to .github/ISSUE_TEMPLATE/question.yml * Add license line to .github/dependabot.yml * Add license line to .github/workflows/ci-testing.yml * Add license line to .github/workflows/cla.yml * Add license line to .github/workflows/codeql-analysis.yml * Add license line to .github/workflows/docker.yml * Add license line to .github/workflows/format.yml * Add license line to .github/workflows/greetings.yml * Add license line to .github/workflows/links.yml * Add license line to .github/workflows/merge-main-into-prs.yml * Add license line to .github/workflows/stale.yml * Add license line to benchmarks.py * Add license line to classify/predict.py * Add license line to classify/train.py * Add license line to classify/val.py * Add license line to data/Argoverse.yaml * Add license line to data/GlobalWheat2020.yaml * Add license line to data/ImageNet.yaml * Add license line to data/ImageNet10.yaml * Add license line to data/ImageNet100.yaml * Add license line to data/ImageNet1000.yaml * Add license line to data/Objects365.yaml * Add license line to data/SKU-110K.yaml * Add license line to data/VOC.yaml * Add license line to data/VisDrone.yaml * Add license line to data/coco.yaml * Add license line to data/coco128-seg.yaml * Add license line to data/coco128.yaml * Add license line to data/hyps/hyp.Objects365.yaml * Add license line to data/hyps/hyp.VOC.yaml * Add license line to data/hyps/hyp.no-augmentation.yaml * Add license line to data/hyps/hyp.scratch-high.yaml * Add license line to data/hyps/hyp.scratch-low.yaml * Add license line to data/hyps/hyp.scratch-med.yaml * Add license line to data/xView.yaml * Add license line to detect.py * Add license line to export.py * Add license line to hubconf.py * Add license line to models/common.py * Add license line to models/experimental.py * Add license line to models/hub/anchors.yaml * Add license line to models/hub/yolov3-spp.yaml * Add license line to models/hub/yolov3-tiny.yaml * Add license line to models/hub/yolov3.yaml * Add license line to models/hub/yolov5-bifpn.yaml * Add license line to models/hub/yolov5-fpn.yaml * Add license line to models/hub/yolov5-p2.yaml * Add license line to models/hub/yolov5-p34.yaml * Add license line to models/hub/yolov5-p6.yaml * Add license line to models/hub/yolov5-p7.yaml * Add license line to models/hub/yolov5-panet.yaml * Add license line to models/hub/yolov5l6.yaml * Add license line to models/hub/yolov5m6.yaml * Add license line to models/hub/yolov5n6.yaml * Add license line to models/hub/yolov5s-LeakyReLU.yaml * Add license line to models/hub/yolov5s-ghost.yaml * Add license line to models/hub/yolov5s-transformer.yaml * Add license line to models/hub/yolov5s6.yaml * Add license line to models/hub/yolov5x6.yaml * Add license line to models/segment/yolov5l-seg.yaml * Add license line to models/segment/yolov5m-seg.yaml * Add license line to models/segment/yolov5n-seg.yaml * Add license line to models/segment/yolov5s-seg.yaml * Add license line to models/segment/yolov5x-seg.yaml * Add license line to models/tf.py * Add license line to models/yolo.py * Add license line to models/yolov5l.yaml * Add license line to models/yolov5m.yaml * Add license line to models/yolov5n.yaml * Add license line to models/yolov5s.yaml * Add license line to models/yolov5x.yaml * Add license line to pyproject.toml * Add license line to segment/predict.py * Add license line to segment/train.py * Add license line to segment/val.py * Add license line to train.py * Add license line to utils/__init__.py * Add license line to utils/activations.py * Add license line to utils/augmentations.py * Add license line to utils/autoanchor.py * Add license line to utils/autobatch.py * Add license line to utils/aws/resume.py * Add license line to utils/callbacks.py * Add license line to utils/dataloaders.py * Add license line to utils/downloads.py * Add license line to utils/flask_rest_api/example_request.py * Add license line to utils/flask_rest_api/restapi.py * Add license line to utils/general.py * Add license line to utils/google_app_engine/app.yaml * Add license line to utils/loggers/__init__.py * Add license line to utils/loggers/clearml/clearml_utils.py * Add license line to utils/loggers/clearml/hpo.py * Add license line to utils/loggers/comet/__init__.py * Add license line to utils/loggers/comet/comet_utils.py * Add license line to utils/loggers/comet/hpo.py * Add license line to utils/loggers/wandb/wandb_utils.py * Add license line to utils/loss.py * Add license line to utils/metrics.py * Add license line to utils/plots.py * Add license line to utils/segment/augmentations.py * Add license line to utils/segment/dataloaders.py * Add license line to utils/segment/general.py * Add license line to utils/segment/loss.py * Add license line to utils/segment/metrics.py * Add license line to utils/segment/plots.py * Add license line to utils/torch_utils.py * Add license line to utils/triton.py * Add license line to val.py * Auto-format by https://ultralytics.com/actions * Update ImageNet1000.yaml Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com> * Auto-format by https://ultralytics.com/actions --------- Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com> Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
137 lines
5.1 KiB
Python
137 lines
5.1 KiB
Python
# Ultralytics YOLOv5 🚀, AGPL-3.0 license
|
|
"""Download utils."""
|
|
|
|
import logging
|
|
import subprocess
|
|
import urllib
|
|
from pathlib import Path
|
|
|
|
import requests
|
|
import torch
|
|
|
|
|
|
def is_url(url, check=True):
|
|
"""Determines if a string is a URL and optionally checks its existence online, returning a boolean."""
|
|
try:
|
|
url = str(url)
|
|
result = urllib.parse.urlparse(url)
|
|
assert all([result.scheme, result.netloc]) # check if is url
|
|
return (urllib.request.urlopen(url).getcode() == 200) if check else True # check if exists online
|
|
except (AssertionError, urllib.request.HTTPError):
|
|
return False
|
|
|
|
|
|
def gsutil_getsize(url=""):
|
|
"""
|
|
Returns the size in bytes of a file at a Google Cloud Storage URL using `gsutil du`.
|
|
|
|
Returns 0 if the command fails or output is empty.
|
|
"""
|
|
output = subprocess.check_output(["gsutil", "du", url], shell=True, encoding="utf-8")
|
|
return int(output.split()[0]) if output else 0
|
|
|
|
|
|
def url_getsize(url="https://ultralytics.com/images/bus.jpg"):
|
|
"""Returns the size in bytes of a downloadable file at a given URL; defaults to -1 if not found."""
|
|
response = requests.head(url, allow_redirects=True)
|
|
return int(response.headers.get("content-length", -1))
|
|
|
|
|
|
def curl_download(url, filename, *, silent: bool = False) -> bool:
|
|
"""Download a file from a url to a filename using curl."""
|
|
silent_option = "sS" if silent else "" # silent
|
|
proc = subprocess.run(
|
|
[
|
|
"curl",
|
|
"-#",
|
|
f"-{silent_option}L",
|
|
url,
|
|
"--output",
|
|
filename,
|
|
"--retry",
|
|
"9",
|
|
"-C",
|
|
"-",
|
|
]
|
|
)
|
|
return proc.returncode == 0
|
|
|
|
|
|
def safe_download(file, url, url2=None, min_bytes=1e0, error_msg=""):
|
|
"""
|
|
Downloads a file from a URL (or alternate URL) to a specified path if file is above a minimum size.
|
|
|
|
Removes incomplete downloads.
|
|
"""
|
|
from utils.general import LOGGER
|
|
|
|
file = Path(file)
|
|
assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}"
|
|
try: # url1
|
|
LOGGER.info(f"Downloading {url} to {file}...")
|
|
torch.hub.download_url_to_file(url, str(file), progress=LOGGER.level <= logging.INFO)
|
|
assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check
|
|
except Exception as e: # url2
|
|
if file.exists():
|
|
file.unlink() # remove partial downloads
|
|
LOGGER.info(f"ERROR: {e}\nRe-attempting {url2 or url} to {file}...")
|
|
# curl download, retry and resume on fail
|
|
curl_download(url2 or url, file)
|
|
finally:
|
|
if not file.exists() or file.stat().st_size < min_bytes: # check
|
|
if file.exists():
|
|
file.unlink() # remove partial downloads
|
|
LOGGER.info(f"ERROR: {assert_msg}\n{error_msg}")
|
|
LOGGER.info("")
|
|
|
|
|
|
def attempt_download(file, repo="ultralytics/yolov5", release="v7.0"):
|
|
"""Downloads a file from GitHub release assets or via direct URL if not found locally, supporting backup
|
|
versions.
|
|
"""
|
|
from utils.general import LOGGER
|
|
|
|
def github_assets(repository, version="latest"):
|
|
# Return GitHub repo tag (i.e. 'v7.0') and assets (i.e. ['yolov5s.pt', 'yolov5m.pt', ...])
|
|
if version != "latest":
|
|
version = f"tags/{version}" # i.e. tags/v7.0
|
|
response = requests.get(f"https://api.github.com/repos/{repository}/releases/{version}").json() # github api
|
|
return response["tag_name"], [x["name"] for x in response["assets"]] # tag, assets
|
|
|
|
file = Path(str(file).strip().replace("'", ""))
|
|
if not file.exists():
|
|
# URL specified
|
|
name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc.
|
|
if str(file).startswith(("http:/", "https:/")): # download
|
|
url = str(file).replace(":/", "://") # Pathlib turns :// -> :/
|
|
file = name.split("?")[0] # parse authentication https://url.com/file.txt?auth...
|
|
if Path(file).is_file():
|
|
LOGGER.info(f"Found {url} locally at {file}") # file already exists
|
|
else:
|
|
safe_download(file=file, url=url, min_bytes=1e5)
|
|
return file
|
|
|
|
# GitHub assets
|
|
assets = [f"yolov5{size}{suffix}.pt" for size in "nsmlx" for suffix in ("", "6", "-cls", "-seg")] # default
|
|
try:
|
|
tag, assets = github_assets(repo, release)
|
|
except Exception:
|
|
try:
|
|
tag, assets = github_assets(repo) # latest release
|
|
except Exception:
|
|
try:
|
|
tag = subprocess.check_output("git tag", shell=True, stderr=subprocess.STDOUT).decode().split()[-1]
|
|
except Exception:
|
|
tag = release
|
|
|
|
if name in assets:
|
|
file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required)
|
|
safe_download(
|
|
file,
|
|
url=f"https://github.com/{repo}/releases/download/{tag}/{name}",
|
|
min_bytes=1e5,
|
|
error_msg=f"{file} missing, try downloading from https://github.com/{repo}/releases/{tag}",
|
|
)
|
|
|
|
return str(file)
|