CLI Simplification (#449)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
Glenn Jocher
2023-01-17 23:00:33 +01:00
committed by GitHub
parent 454191bd4b
commit 453b5f259a
16 changed files with 218 additions and 132 deletions

View File

@ -10,6 +10,7 @@ import tempfile
import threading
import uuid
from pathlib import Path
from typing import Union
import cv2
import git
@ -41,12 +42,15 @@ HELP_MSG = \
from ultralytics import YOLO
model = YOLO('yolov8n.yaml') # build a new model from scratch
model = YOLO('yolov8n.pt') # load a pretrained model (recommended for best training results)
results = model.train(data='coco128.yaml') # train the model
results = model.val() # evaluate model performance on the validation set
results = model.predict(source='bus.jpg') # predict on an image
success = model.export(format='onnx') # export the model to ONNX format
# Load a model
model = YOLO("yolov8n.yaml") # build a new model from scratch
model = YOLO("yolov8n.pt") # load a pretrained model (recommended for training)
# Use the model
results = model.train(data="coco128.yaml", epochs=3) # train the model
results = model.val() # evaluate model performance on the validation set
results = model("https://ultralytics.com/images/bus.jpg") # predict on an image
success = model.export(format="onnx") # export the model to ONNX format
3. Use the command line interface (CLI):
@ -161,12 +165,12 @@ def is_pip_package(filepath: str = __name__) -> bool:
return spec is not None and spec.origin is not None
def is_dir_writeable(dir_path: str) -> bool:
def is_dir_writeable(dir_path: Union[str, Path]) -> bool:
"""
Check if a directory is writeable.
Args:
dir_path (str): The path to the directory.
dir_path (str) or (Path): The path to the directory.
Returns:
bool: True if the directory is writeable, False otherwise.
@ -179,6 +183,18 @@ def is_dir_writeable(dir_path: str) -> bool:
return False
def is_pytest_running():
"""
Returns a boolean indicating if pytest is currently running or not
:return: True if pytest is running, False otherwise
"""
try:
import sys
return "pytest" in sys.modules
except ImportError:
return False
def get_git_root_dir():
"""
Determines whether the current file is part of a git repository and if so, returns the repository root directory.
@ -348,6 +364,17 @@ def yaml_load(file='data.yaml', append_filename=False):
return {**yaml.safe_load(f), 'yaml_file': str(file)} if append_filename else yaml.safe_load(f)
def set_sentry(dsn=None):
"""
Initialize the Sentry SDK for error tracking and reporting if pytest is not currently running.
"""
if dsn and not is_pytest_running():
import sentry_sdk # noqa
import ultralytics
sentry_sdk.init(dsn=dsn, traces_sample_rate=1.0, release=ultralytics.__version__, debug=False)
def get_settings(file=USER_CONFIG_DIR / 'settings.yaml', version='0.0.1'):
"""
Loads a global Ultralytics settings YAML file or creates one with default values if it does not exist.
@ -364,8 +391,9 @@ def get_settings(file=USER_CONFIG_DIR / 'settings.yaml', version='0.0.1'):
is_git = is_git_directory() # True if ultralytics installed via git
root = get_git_root_dir() if is_git else Path()
datasets_root = (root.parent if (is_git and is_dir_writeable(root.parent)) else root).resolve()
defaults = {
'datasets_dir': str((root.parent if is_git else root) / 'datasets'), # default datasets directory.
'datasets_dir': str(datasets_root / 'datasets'), # default datasets directory.
'weights_dir': str(root / 'weights'), # default weights directory.
'runs_dir': str(root / 'runs'), # default runs directory.
'sync': True, # sync analytics to help with YOLO development
@ -393,6 +421,26 @@ def get_settings(file=USER_CONFIG_DIR / 'settings.yaml', version='0.0.1'):
return settings
def set_settings(kwargs, file=USER_CONFIG_DIR / 'settings.yaml'):
"""
Function that runs on a first-time ultralytics package installation to set up global settings and create necessary
directories.
"""
SETTINGS.update(kwargs)
yaml_save(file, SETTINGS)
def print_settings():
"""
Function that prints Ultralytics settings
"""
import json
s = f'\n{PREFIX}Settings:\n'
s += json.dumps(SETTINGS, indent=2)
s += f"\n\nUpdate settings at {USER_CONFIG_DIR / 'settings.yaml'}"
LOGGER.info(s)
# Run below code on utils init -----------------------------------------------------------------------------------------
# Set logger
@ -403,15 +451,7 @@ if platform.system() == 'Windows':
setattr(LOGGER, fn.__name__, lambda x: fn(emojis(x))) # emoji safe logging
# Check first-install steps
PREFIX = colorstr("Ultralytics: ")
SETTINGS = get_settings()
DATASETS_DIR = Path(SETTINGS['datasets_dir']) # global datasets directory
def set_settings(kwargs, file=USER_CONFIG_DIR / 'settings.yaml'):
"""
Function that runs on a first-time ultralytics package installation to set up global settings and create necessary
directories.
"""
SETTINGS.update(kwargs)
yaml_save(file, SETTINGS)
set_sentry()