diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index 082605f..50a5482 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -26,16 +26,7 @@ jobs:
- uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- - name: Get cache dir # https://github.com/actions/cache/blob/master/examples.md#multiple-oss-in-a-workflow
- id: pip-cache
- run: echo "dir=$(pip cache dir)" >> $GITHUB_OUTPUT
- shell: bash # for Windows compatibility
- - name: Cache pip
- uses: actions/cache@v3
- with:
- path: ${{ steps.pip-cache.outputs.dir }}
- key: ${{ runner.os }}-${{ matrix.python-version }}-pip-${{ hashFiles('requirements.txt') }}
- restore-keys: ${{ runner.os }}-${{ matrix.python-version }}-pip-
+ cache: 'pip' # caching pip dependencies
- name: Install requirements
shell: bash # for Windows compatibility
run: |
@@ -76,16 +67,7 @@ jobs:
- uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- - name: Get cache dir # https://github.com/actions/cache/blob/master/examples.md#multiple-oss-in-a-workflow
- id: pip-cache
- run: echo "dir=$(pip cache dir)" >> $GITHUB_OUTPUT
- shell: bash # for Windows compatibility
- - name: Cache pip
- uses: actions/cache@v3
- with:
- path: ${{ steps.pip-cache.outputs.dir }}
- key: ${{ runner.os }}-${{ matrix.python-version }}-pip-${{ hashFiles('requirements.txt') }}
- restore-keys: ${{ runner.os }}-${{ matrix.python-version }}-pip-
+ cache: 'pip' # caching pip dependencies
- name: Install requirements
shell: bash # for Windows compatibility
run: |
@@ -145,16 +127,7 @@ jobs:
- uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- - name: Get cache dir # https://github.com/actions/cache/blob/master/examples.md#multiple-oss-in-a-workflow
- id: pip-cache
- run: echo "dir=$(pip cache dir)" >> $GITHUB_OUTPUT
- shell: bash # for Windows compatibility
- - name: Cache pip
- uses: actions/cache@v3
- with:
- path: ${{ steps.pip-cache.outputs.dir }}
- key: ${{ runner.os }}-${{ matrix.python-version }}-pip-${{ hashFiles('requirements.txt') }}
- restore-keys: ${{ runner.os }}-${{ matrix.python-version }}-pip-
+ cache: 'pip' # caching pip dependencies
- name: Install requirements
shell: bash # for Windows compatibility
run: |
diff --git a/.github/workflows/greetings.yml b/.github/workflows/greetings.yml
new file mode 100644
index 0000000..f843652
--- /dev/null
+++ b/.github/workflows/greetings.yml
@@ -0,0 +1,55 @@
+# Ultralytics YOLO 🚀, GPL-3.0 license
+
+name: Greetings
+
+on:
+ pull_request_target:
+ types: [opened]
+ issues:
+ types: [opened]
+
+jobs:
+ greeting:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/first-interaction@v1
+ with:
+ repo-token: ${{ secrets.GITHUB_TOKEN }}
+ pr-message: |
+ 👋 Hello @${{ github.actor }}, thank you for submitting a YOLOv8 🚀 PR! To allow your work to be integrated as seamlessly as possible, we advise you to:
+
+ - ✅ Verify your PR is **up-to-date** with `ultralytics/ultralytics` `main` branch. If your PR is behind you can update your code by clicking the 'Update branch' button or by running `git pull` and `git merge master` locally.
+ - ✅ Verify all YOLOv8 Continuous Integration (CI) **checks are passing**.
+ - ✅ Reduce changes to the absolute **minimum** required for your bug fix or feature addition. _"It is not daily increase but daily decrease, hack away the unessential. The closer to the source, the less wastage there is."_ — Bruce Lee
+
+ See our [Contributing Guide](https://github.com/ultralytics/ultralytics/blob/main/CONTRIBUTING.md) for details and let us know if you have any questions!
+
+ issue-message: |
+ 👋 Hello @${{ github.actor }}, thank you for your interest in YOLOv8 🚀! We recommend a visit to the [YOLOv8 Docs](https://docs.ultralytics.com) for new users where you can find many [Python](https://docs.ultralytics.com/python/) and [CLI](https://docs.ultralytics.com/cli/) usage examples and where many of the most common questions may already be answered.
+
+ If this is a 🐛 Bug Report, please provide a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) to help us debug it.
+
+ If this is a custom training ❓ Question, please provide as much information as possible, including dataset image examples and training logs, and verify you are following our [Tips for Best Training Results](https://github.com/ultralytics/yolov5/wiki/Tips-for-Best-Training-Results).
+
+ ## Install
+
+ Pip install the `ultralytics` package including all [requirements.txt](https://github.com/ultralytics/ultralytics/blob/main/requirements.txt) in a [**Python>=3.7**](https://www.python.org/) environment with [**PyTorch>=1.7**](https://pytorch.org/get-started/locally/).
+
+ ```bash
+ pip install ultralytics
+ ```
+
+ ## Environments
+
+ YOLOv8 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):
+
+ - **Notebooks** with free GPU:
+ - **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart)
+ - **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart)
+ - **Docker Image**. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart)
+
+ ## Status
+
+
+
+ If this badge is green, all [Ultralytics CI](https://github.com/ultralytics/ultralytics/actions/workflows/ci.yaml?query=event%3Aschedule) tests are currently passing. CI tests verify correct operation of all YOLOv8 modes and tasks on macOS, Windows, and Ubuntu every 24 hours and on every commit.
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
new file mode 100644
index 0000000..4b5364b
--- /dev/null
+++ b/.github/workflows/publish.yml
@@ -0,0 +1,67 @@
+# Ultralytics YOLO 🚀, GPL-3.0 license
+# Publish pip package to PyPI https://pypi.org/project/ultralytics/ and Docs to https://docs.ultralytics.com
+
+name: Publish to PyPI and Deploy Docs
+
+on:
+ workflow_dispatch:
+ inputs:
+ pypi:
+ type: boolean
+ description: Publish to PyPI
+ docs:
+ type: boolean
+ description: Deploy Docs
+ push:
+ branches: [main]
+
+jobs:
+ publish:
+ if: github.repository == 'ultralytics/ultralytics' && github.actor == 'glenn-jocher'
+ name: Publish
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v3
+ - name: Set up Python environment
+ uses: actions/setup-python@v4
+ with:
+ python-version: '3.10'
+ cache: 'pip' # caching pip dependencies
+ - name: Install dependencies
+ run: |
+ python -m pip install --upgrade pip wheel build twine
+ pip install -e '.[dev]' --extra-index-url https://download.pytorch.org/whl/cpu
+ - name: Check PyPI version
+ shell: python
+ run: |
+ import pkg_resources as pkg
+ import ultralytics
+ import os
+ from ultralytics.yolo.utils.checks import check_latest_pypi_version
+
+ v_local = pkg.parse_version(ultralytics.__version__).release
+ v_pypi = pkg.parse_version(check_latest_pypi_version()).release
+ print(f'Local version is {v_local}')
+ print(f'PyPI version is {v_pypi}')
+ d = [a - b for a, b in zip(v_local, v_pypi)] # diff
+ increment = (d[0] == d[1] == 0) and d[2] == 1 # only patch increment by 1
+ os.system(f'echo "increment={increment}" >> $GITHUB_OUTPUT')
+ if increment:
+ print('Local version is higher than PyPI version. Publishing new version to PyPI ✅.')
+ id: check_pypi
+ - name: Publish to PyPI
+ continue-on-error: true
+ if: (github.event_name == 'push' || github.event.inputs.pypi == 'true') && steps.check_pypi.outputs.increment == 'True'
+ env:
+ PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
+ run: |
+ python -m build
+ python -m twine upload dist/* -u __token__ -p $PYPI_TOKEN
+ - name: Deploy Docs
+ continue-on-error: true
+ if: (github.event_name == 'push' && steps.check_pypi.outputs.increment == 'True') || github.event.inputs.docs == 'true'
+ run: |
+ mkdocs gh-deploy || true
+ git checkout gh-pages
+ git push https://github.com/ultralytics/docs gh-pages --force
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml
new file mode 100644
index 0000000..82c881c
--- /dev/null
+++ b/.github/workflows/stale.yml
@@ -0,0 +1,47 @@
+# Ultralytics YOLO 🚀, GPL-3.0 license
+
+name: Close stale issues
+on:
+ schedule:
+ - cron: '0 0 * * *' # Runs at 00:00 UTC every day
+
+jobs:
+ stale:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/stale@v7
+ with:
+ repo-token: ${{ secrets.GITHUB_TOKEN }}
+
+ stale-issue-message: |
+ 👋 Hello there! We wanted to give you a friendly reminder that this issue has not had any recent activity and may be closed soon, but don't worry - you can always reopen it if needed. If you still have any questions or concerns, please feel free to let us know how we can help.
+
+ For additional resources and information, please see the links below:
+
+ - **Docs**: https://docs.ultralytics.com
+ - **HUB**: https://hub.ultralytics.com
+ - **Community**: https://community.ultralytics.com
+
+ Feel free to inform us of any other **issues** you discover or **feature requests** that come to mind in the future. Pull Requests (PRs) are also always welcomed!
+
+ Thank you for your contributions to YOLO 🚀 and Vision AI ⭐
+
+ stale-pr-message: |
+ 👋 Hello there! We wanted to let you know that we've decided to close this pull request due to inactivity. We appreciate the effort you put into contributing to our project, but unfortunately, not all contributions are suitable or aligned with our product roadmap.
+
+ We hope you understand our decision, and please don't let it discourage you from contributing to open source projects in the future. We value all of our community members and their contributions, and we encourage you to keep exploring new projects and ways to get involved.
+
+ For additional resources and information, please see the links below:
+
+ - **Docs**: https://docs.ultralytics.com
+ - **HUB**: https://hub.ultralytics.com
+ - **Community**: https://community.ultralytics.com
+
+ Thank you for your contributions to YOLO 🚀 and Vision AI ⭐
+
+ days-before-issue-stale: 30
+ days-before-issue-close: 10
+ days-before-pr-stale: 90
+ days-before-pr-close: 30
+ exempt-issue-labels: 'documentation,tutorial,TODO'
+ operations-per-run: 300 # The maximum number of operations per run, used to control rate limiting.
diff --git a/MANIFEST.in b/MANIFEST.in
index f37cd80..def1ad3 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -2,5 +2,7 @@ include *.md
include requirements.txt
include LICENSE
include setup.py
+include ultralytics/assets/bus.jpg
+include ultralytics/assets/zidane.jpg
recursive-include ultralytics *.yaml
recursive-exclude __pycache__ *
diff --git a/requirements.txt b/requirements.txt
index eb4b7fe..98480e6 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -14,7 +14,7 @@ torchvision>=0.8.1
tqdm>=4.64.0
# Logging -------------------------------------
-tensorboard>=2.4.1
+# tensorboard>=2.4.1
# clearml
# comet
@@ -41,4 +41,3 @@ thop>=0.1.1 # FLOPs computation
# albumentations>=1.0.3
# pycocotools>=2.0.6 # COCO mAP
# roboflow
-certifi>=2022.12.7 # not directly required, pinned by Snyk to avoid a vulnerability
diff --git a/ultralytics/__init__.py b/ultralytics/__init__.py
index 403b610..2e78eaa 100644
--- a/ultralytics/__init__.py
+++ b/ultralytics/__init__.py
@@ -1,6 +1,6 @@
# Ultralytics YOLO 🚀, GPL-3.0 license
-__version__ = '8.0.50'
+__version__ = '8.0.51'
from ultralytics.yolo.engine.model import YOLO
from ultralytics.yolo.utils.checks import check_yolo as checks
diff --git a/ultralytics/assets/bus.jpg b/ultralytics/assets/bus.jpg
index b43e311..40eaaf5 100644
Binary files a/ultralytics/assets/bus.jpg and b/ultralytics/assets/bus.jpg differ
diff --git a/ultralytics/assets/zidane.jpg b/ultralytics/assets/zidane.jpg
index 92d72ea..eeab1cd 100644
Binary files a/ultralytics/assets/zidane.jpg and b/ultralytics/assets/zidane.jpg differ
diff --git a/ultralytics/nn/autobackend.py b/ultralytics/nn/autobackend.py
index 9b7aa1a..bf80c1b 100644
--- a/ultralytics/nn/autobackend.py
+++ b/ultralytics/nn/autobackend.py
@@ -14,7 +14,7 @@ import torch
import torch.nn as nn
from PIL import Image
-from ultralytics.yolo.utils import LOGGER, ROOT, yaml_load
+from ultralytics.yolo.utils import LINUX, LOGGER, ROOT, yaml_load
from ultralytics.yolo.utils.checks import check_requirements, check_suffix, check_version, check_yaml
from ultralytics.yolo.utils.downloads import attempt_download_asset, is_url
from ultralytics.yolo.utils.ops import xywh2xyxy
@@ -143,7 +143,12 @@ class AutoBackend(nn.Module):
metadata = w.parent / 'metadata.yaml'
elif engine: # TensorRT
LOGGER.info(f'Loading {w} for TensorRT inference...')
- import tensorrt as trt # https://developer.nvidia.com/nvidia-tensorrt-download
+ try:
+ import tensorrt as trt # noqa https://developer.nvidia.com/nvidia-tensorrt-download
+ except ImportError:
+ if LINUX:
+ check_requirements('nvidia-tensorrt', cmds='-U --index-url https://pypi.ngc.nvidia.com')
+ import tensorrt as trt # noqa
check_version(trt.__version__, '7.0.0', hard=True) # require tensorrt>=7.0.0
if device.type == 'cpu':
device = torch.device('cuda:0')
@@ -230,7 +235,7 @@ class AutoBackend(nn.Module):
elif paddle: # PaddlePaddle
LOGGER.info(f'Loading {w} for PaddlePaddle inference...')
check_requirements('paddlepaddle-gpu' if cuda else 'paddlepaddle')
- import paddle.inference as pdi
+ import paddle.inference as pdi # noqa
w = Path(w)
if not w.is_file(): # if not *.pdmodel
w = next(w.rglob('*.pdmodel')) # get *.pdmodel file from *_paddle_model dir
@@ -260,11 +265,16 @@ class AutoBackend(nn.Module):
if isinstance(metadata, (str, Path)) and Path(metadata).exists():
metadata = yaml_load(metadata)
if metadata:
- stride = int(metadata['stride'])
+ for k, v in metadata.items():
+ if k in ('stride', 'batch'):
+ metadata[k] = int(v)
+ elif k in ('imgsz', 'names') and isinstance(v, str):
+ metadata[k] = eval(v)
+ stride = metadata['stride']
task = metadata['task']
- batch = int(metadata['batch'])
- imgsz = eval(metadata['imgsz']) if isinstance(metadata['imgsz'], str) else metadata['imgsz']
- names = eval(metadata['names']) if isinstance(metadata['names'], str) else metadata['names']
+ batch = metadata['batch']
+ imgsz = metadata['imgsz']
+ names = metadata['names']
elif not (pt or triton or nn_module):
LOGGER.warning(f"WARNING ⚠️ Metadata not found for 'model={weights}'")
@@ -285,7 +295,7 @@ class AutoBackend(nn.Module):
visualize (bool): whether to visualize the output predictions, defaults to False
Returns:
- (tuple): Tuple containing the raw output tensor, and the processed output for visualization (if visualize=True)
+ (tuple): Tuple containing the raw output tensor, and processed output for visualization (if visualize=True)
"""
b, ch, h, w = im.shape # batch, channel, height, width
if self.fp16 and im.dtype != torch.float16:
diff --git a/ultralytics/nn/modules.py b/ultralytics/nn/modules.py
index 7494028..fcc599f 100644
--- a/ultralytics/nn/modules.py
+++ b/ultralytics/nn/modules.py
@@ -67,7 +67,8 @@ class ConvTranspose(nn.Module):
class DFL(nn.Module):
- # Integral module of Distribution Focal Loss (DFL) proposed in Generalized Focal Loss https://ieeexplore.ieee.org/document/9792391
+ # Integral module of Distribution Focal Loss (DFL)
+ # Proposed in Generalized Focal Loss https://ieeexplore.ieee.org/document/9792391
def __init__(self, c1=16):
super().__init__()
self.conv = nn.Conv2d(c1, 1, 1, bias=False).requires_grad_(False)
diff --git a/ultralytics/nn/tasks.py b/ultralytics/nn/tasks.py
index 9cab0c4..c453b69 100644
--- a/ultralytics/nn/tasks.py
+++ b/ultralytics/nn/tasks.py
@@ -8,7 +8,9 @@ import thop
import torch
import torch.nn as nn
-from ultralytics.nn.modules import * # noqa: F403
+from ultralytics.nn.modules import (C1, C2, C3, C3TR, SPP, SPPF, Bottleneck, BottleneckCSP, C2f, C3Ghost, C3x, Classify,
+ Concat, Conv, ConvTranspose, Detect, DWConv, DWConvTranspose2d, Ensemble, Focus,
+ GhostBottleneck, GhostConv, Segment)
from ultralytics.yolo.utils import DEFAULT_CFG_DICT, DEFAULT_CFG_KEYS, LOGGER, RANK, colorstr, emojis, yaml_load
from ultralytics.yolo.utils.checks import check_requirements, check_yaml
from ultralytics.yolo.utils.torch_utils import (fuse_conv_and_bn, fuse_deconv_and_bn, initialize_weights,
@@ -324,9 +326,9 @@ class ClassificationModel(BaseModel):
def torch_safe_load(weight):
"""
- This function attempts to load a PyTorch model with the torch.load() function. If a ModuleNotFoundError is raised, it
- catches the error, logs a warning message, and attempts to install the missing module via the check_requirements()
- function. After installation, the function again attempts to load the model using torch.load().
+ This function attempts to load a PyTorch model with the torch.load() function. If a ModuleNotFoundError is raised,
+ it catches the error, logs a warning message, and attempts to install the missing module via the
+ check_requirements() function. After installation, the function again attempts to load the model using torch.load().
Args:
weight (str): The file path of the PyTorch model.
diff --git a/ultralytics/tracker/utils/matching.py b/ultralytics/tracker/utils/matching.py
index 7d9d0fb..02ff75c 100644
--- a/ultralytics/tracker/utils/matching.py
+++ b/ultralytics/tracker/utils/matching.py
@@ -40,7 +40,10 @@ def linear_assignment(cost_matrix, thresh):
if cost_matrix.size == 0:
return np.empty((0, 2), dtype=int), tuple(range(cost_matrix.shape[0])), tuple(range(cost_matrix.shape[1]))
matches, unmatched_a, unmatched_b = [], [], []
+
+ # TODO: investigate scipy.optimize.linear_sum_assignment() for lap.lapjv()
cost, x, y = lap.lapjv(cost_matrix, extend_cost=True, cost_limit=thresh)
+
matches.extend([ix, mx] for ix, mx in enumerate(x) if mx >= 0)
unmatched_a = np.where(x < 0)[0]
unmatched_b = np.where(y < 0)[0]
diff --git a/ultralytics/yolo/cfg/__init__.py b/ultralytics/yolo/cfg/__init__.py
index c38c93d..22b6719 100644
--- a/ultralytics/yolo/cfg/__init__.py
+++ b/ultralytics/yolo/cfg/__init__.py
@@ -327,4 +327,4 @@ def copy_default_cfg():
if __name__ == '__main__':
# entrypoint(debug='yolo predict model=yolov8n.pt')
- entrypoint(debug='yolo train model=yolov8n-seg.pt')
+ entrypoint(debug='')
diff --git a/ultralytics/yolo/data/utils.py b/ultralytics/yolo/data/utils.py
index 5a96fb9..9b15ee6 100644
--- a/ultralytics/yolo/data/utils.py
+++ b/ultralytics/yolo/data/utils.py
@@ -210,8 +210,7 @@ def check_det_dataset(dataset, autodownload=True):
for k in 'train', 'val', 'names':
if k not in data:
raise SyntaxError(
- emojis(f"{dataset} '{k}:' key missing ❌.\n"
- f"'train', 'val' and 'names' are required in data.yaml files."))
+ emojis(f"{dataset} '{k}:' key missing ❌.\n'train', 'val' and 'names' are required in all data YAMLs."))
data['names'] = check_class_names(data['names'])
data['nc'] = len(data['names'])
@@ -236,11 +235,11 @@ def check_det_dataset(dataset, autodownload=True):
if val:
val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path
if not all(x.exists() for x in val):
- msg = f"\nDataset '{dataset}' not found ⚠️, missing paths %s" % [str(x) for x in val if not x.exists()]
+ m = f"\nDataset '{dataset}' images not found ⚠️, missing paths %s" % [str(x) for x in val if not x.exists()]
if s and autodownload:
- LOGGER.warning(msg)
+ LOGGER.warning(m)
else:
- raise FileNotFoundError(msg)
+ raise FileNotFoundError(m)
t = time.time()
if s.startswith('http') and s.endswith('.zip'): # URL
safe_download(url=s, dir=DATASETS_DIR, delete=True)
diff --git a/ultralytics/yolo/engine/exporter.py b/ultralytics/yolo/engine/exporter.py
index 477b6e2..7f690c6 100644
--- a/ultralytics/yolo/engine/exporter.py
+++ b/ultralytics/yolo/engine/exporter.py
@@ -69,7 +69,7 @@ from ultralytics.yolo.data.dataloaders.stream_loaders import LoadImages
from ultralytics.yolo.data.utils import IMAGENET_MEAN, IMAGENET_STD, check_det_dataset
from ultralytics.yolo.utils import (DEFAULT_CFG, LINUX, LOGGER, MACOS, __version__, callbacks, colorstr,
get_default_args, yaml_save)
-from ultralytics.yolo.utils.checks import check_imgsz, check_requirements, check_version, check_yaml
+from ultralytics.yolo.utils.checks import check_imgsz, check_requirements, check_version
from ultralytics.yolo.utils.files import file_size
from ultralytics.yolo.utils.ops import Profile
from ultralytics.yolo.utils.torch_utils import get_latest_opset, select_device, smart_inference_mode
@@ -601,7 +601,7 @@ class Exporter:
if n >= n_images:
break
- dataset = LoadImages(check_det_dataset(check_yaml(self.args.data))['train'], imgsz=imgsz, auto=False)
+ dataset = LoadImages(check_det_dataset(self.args.data)['train'], imgsz=imgsz, auto=False)
converter.representative_dataset = lambda: representative_dataset_gen(dataset, n_images=100)
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.target_spec.supported_types = []
diff --git a/ultralytics/yolo/engine/model.py b/ultralytics/yolo/engine/model.py
index b86dca7..fecca7e 100644
--- a/ultralytics/yolo/engine/model.py
+++ b/ultralytics/yolo/engine/model.py
@@ -10,7 +10,7 @@ from ultralytics.yolo.cfg import get_cfg
from ultralytics.yolo.engine.exporter import Exporter
from ultralytics.yolo.utils import (DEFAULT_CFG, DEFAULT_CFG_DICT, DEFAULT_CFG_KEYS, LOGGER, ONLINE, RANK, ROOT,
callbacks, is_git_dir, is_pip_package, yaml_load)
-from ultralytics.yolo.utils.checks import check_file, check_imgsz, check_pip_update, check_yaml
+from ultralytics.yolo.utils.checks import check_file, check_imgsz, check_pip_update_available, check_yaml
from ultralytics.yolo.utils.downloads import GITHUB_ASSET_STEMS
from ultralytics.yolo.utils.torch_utils import smart_inference_mode
@@ -158,7 +158,7 @@ class YOLO:
Inform user of ultralytics package update availability
"""
if ONLINE and is_pip_package():
- check_pip_update()
+ check_pip_update_available()
def reset(self):
"""
diff --git a/ultralytics/yolo/engine/results.py b/ultralytics/yolo/engine/results.py
index d84b05b..ef4ec94 100644
--- a/ultralytics/yolo/engine/results.py
+++ b/ultralytics/yolo/engine/results.py
@@ -263,8 +263,11 @@ class Boxes:
return self.boxes.__str__()
def __repr__(self):
- return (f'Ultralytics YOLO {self.__class__.__name__}\n' + f'type: {type(self.boxes)}\n' +
- f'shape: {self.boxes.shape}\n' + f'dtype: {self.boxes.dtype}\n + {self.boxes.__repr__()}')
+ return (f'{self.__class__.__module__}.{self.__class__.__name__}\n'
+ f'type: {self.boxes.__class__.__module__}.{self.boxes.__class__.__name__}\n'
+ f'shape: {self.boxes.shape}\n'
+ f'dtype: {self.boxes.dtype}\n'
+ f'{self.boxes.__repr__()}')
def __getitem__(self, idx):
return Boxes(self.boxes[idx], self.orig_shape)
@@ -339,8 +342,11 @@ class Masks:
return self.masks.__str__()
def __repr__(self):
- return (f'Ultralytics YOLO {self.__class__.__name__}\n' + f'type: {type(self.masks)}\n' +
- f'shape: {self.masks.shape}\n' + f'dtype: {self.masks.dtype}\n + {self.masks.__repr__()}')
+ return (f'{self.__class__.__module__}.{self.__class__.__name__}\n'
+ f'type: {self.masks.__class__.__module__}.{self.masks.__class__.__name__}\n'
+ f'shape: {self.masks.shape}\n'
+ f'dtype: {self.masks.dtype}\n'
+ f'{self.masks.__repr__()}')
def __getitem__(self, idx):
return Masks(self.masks[idx], self.orig_shape)
diff --git a/ultralytics/yolo/utils/__init__.py b/ultralytics/yolo/utils/__init__.py
index f0a269a..d95837d 100644
--- a/ultralytics/yolo/utils/__init__.py
+++ b/ultralytics/yolo/utils/__init__.py
@@ -126,6 +126,37 @@ class IterableSimpleNamespace(SimpleNamespace):
return getattr(self, key, default)
+def set_logging(name=LOGGING_NAME, verbose=True):
+ # sets up logging for the given name
+ rank = int(os.getenv('RANK', -1)) # rank in world for Multi-GPU trainings
+ level = logging.INFO if verbose and rank in {-1, 0} else logging.ERROR
+ logging.config.dictConfig({
+ 'version': 1,
+ 'disable_existing_loggers': False,
+ 'formatters': {
+ name: {
+ 'format': '%(message)s'}},
+ 'handlers': {
+ name: {
+ 'class': 'logging.StreamHandler',
+ 'formatter': name,
+ 'level': level}},
+ 'loggers': {
+ name: {
+ 'level': level,
+ 'handlers': [name],
+ 'propagate': False}}})
+
+
+# Set logger
+set_logging(LOGGING_NAME, verbose=VERBOSE) # run before defining LOGGER
+LOGGER = logging.getLogger(LOGGING_NAME) # define globally (used in train.py, val.py, detect.py, etc.)
+if WINDOWS: # emoji-safe logging
+ info_fn, warning_fn = LOGGER.info, LOGGER.warning
+ setattr(LOGGER, info_fn.__name__, lambda x: info_fn(emojis(x)))
+ setattr(LOGGER, warning_fn.__name__, lambda x: warning_fn(emojis(x)))
+
+
def yaml_save(file='data.yaml', data=None):
"""
Save YAML data to a file.
@@ -163,10 +194,13 @@ def yaml_load(file='data.yaml', append_filename=False):
dict: YAML data and file name.
"""
with open(file, errors='ignore', encoding='utf-8') as f:
- # Add YAML filename to dict and return
s = f.read() # string
- if not s.isprintable(): # remove special characters
+
+ # Remove special characters
+ if not s.isprintable():
s = re.sub(r'[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]+', '', s)
+
+ # Add YAML filename to dict and return
return {**yaml.safe_load(s), 'yaml_file': str(file)} if append_filename else yaml.safe_load(s)
@@ -448,41 +482,6 @@ def colorstr(*input):
return ''.join(colors[x] for x in args) + f'{string}' + colors['end']
-def remove_ansi_codes(string):
- """
- Remove ANSI escape sequences from a string.
-
- Args:
- string (str): The input string that may contain ANSI escape sequences.
-
- Returns:
- str: The input string with ANSI escape sequences removed.
- """
- return re.sub(r'\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]', '', string)
-
-
-def set_logging(name=LOGGING_NAME, verbose=True):
- # sets up logging for the given name
- rank = int(os.getenv('RANK', -1)) # rank in world for Multi-GPU trainings
- level = logging.INFO if verbose and rank in {-1, 0} else logging.ERROR
- logging.config.dictConfig({
- 'version': 1,
- 'disable_existing_loggers': False,
- 'formatters': {
- name: {
- 'format': '%(message)s'}},
- 'handlers': {
- name: {
- 'class': 'logging.StreamHandler',
- 'formatter': name,
- 'level': level}},
- 'loggers': {
- name: {
- 'level': level,
- 'handlers': [name],
- 'propagate': False}}})
-
-
class TryExcept(contextlib.ContextDecorator):
# YOLOv8 TryExcept class. Usage: @TryExcept() decorator or 'with TryExcept():' context manager
def __init__(self, msg='', verbose=True):
@@ -609,13 +608,6 @@ def set_settings(kwargs, file=USER_CONFIG_DIR / 'settings.yaml'):
# Run below code on yolo/utils init ------------------------------------------------------------------------------------
-# Set logger
-set_logging(LOGGING_NAME, verbose=VERBOSE) # run before defining LOGGER
-LOGGER = logging.getLogger(LOGGING_NAME) # define globally (used in train.py, val.py, detect.py, etc.)
-if WINDOWS:
- for fn in LOGGER.info, LOGGER.warning:
- setattr(LOGGER, fn.__name__, lambda x: fn(emojis(x))) # emoji safe logging
-
# Check first-install steps
PREFIX = colorstr('Ultralytics: ')
SETTINGS = get_settings()
diff --git a/ultralytics/yolo/utils/checks.py b/ultralytics/yolo/utils/checks.py
index 4d3a908..891bac8 100644
--- a/ultralytics/yolo/utils/checks.py
+++ b/ultralytics/yolo/utils/checks.py
@@ -134,12 +134,20 @@ def check_latest_pypi_version(package_name='ultralytics'):
return None
-def check_pip_update():
+def check_pip_update_available():
+ """
+ Checks if a new version of the ultralytics package is available on PyPI.
+
+ Returns:
+ bool: True if an update is available, False otherwise.
+ """
from ultralytics import __version__
latest = check_latest_pypi_version()
- if pkg.parse_version(__version__) < pkg.parse_version(latest):
+ if pkg.parse_version(__version__) < pkg.parse_version(latest): # update is available
LOGGER.info(f'New https://pypi.org/project/ultralytics/{latest} available 😃 '
f"Update with 'pip install -U ultralytics'")
+ return True
+ return False
def check_font(font='Arial.ttf'):
diff --git a/ultralytics/yolo/utils/plotting.py b/ultralytics/yolo/utils/plotting.py
index dd94d59..33c95d6 100644
--- a/ultralytics/yolo/utils/plotting.py
+++ b/ultralytics/yolo/utils/plotting.py
@@ -9,7 +9,6 @@ import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
-import seaborn as sn
import torch
from PIL import Image, ImageDraw, ImageFont
from PIL import __version__ as pil_version
@@ -161,6 +160,8 @@ class Annotator:
@TryExcept() # known issue https://github.com/ultralytics/yolov5/issues/5395
def plot_labels(boxes, cls, names=(), save_dir=Path('')):
+ import seaborn as sn
+
# plot dataset labels
LOGGER.info(f"Plotting labels to {save_dir / 'labels.jpg'}... ")
b = boxes.transpose() # classes, boxes