Skip to content

Commit

Permalink
Remove GitPython dependency (ultralytics#568)
Browse files Browse the repository at this point in the history
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
glenn-jocher and pre-commit-ci[bot] authored Jan 23, 2023
1 parent 3c4de10 commit d6a4ffb
Show file tree
Hide file tree
Showing 9 changed files with 138 additions and 58 deletions.
5 changes: 5 additions & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ theme:
- navigation.footer
- content.tabs.link # all code tabs change simultaneously

# Version drop-down menu
# extra:
# version:
# provider: mike

extra_css:
- stylesheets/style.css

Expand Down
5 changes: 1 addition & 4 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# Base ----------------------------------------
matplotlib>=3.2.2
numpy>=1.18.5
opencv-python>=4.1.1
opencv-python>=4.6.0
Pillow>=7.1.2
PyYAML>=5.3.1
requests>=2.23.0
Expand Down Expand Up @@ -40,6 +40,3 @@ thop>=0.1.1 # FLOPs computation
# albumentations>=1.0.3
# pycocotools>=2.0.6 # COCO mAP
# roboflow

# HUB -----------------------------------------
GitPython>=3.1.24
2 changes: 1 addition & 1 deletion ultralytics/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Ultralytics YOLO 🚀, GPL-3.0 license

__version__ = "8.0.15"
__version__ = "8.0.17"

from ultralytics.yolo.engine.model import YOLO
from ultralytics.yolo.utils import ops
Expand Down
13 changes: 11 additions & 2 deletions ultralytics/nn/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
Concat, Conv, ConvTranspose, Detect, DWConv, DWConvTranspose2d, Ensemble, Focus,
GhostBottleneck, GhostConv, Segment)
from ultralytics.yolo.utils import DEFAULT_CFG_DICT, DEFAULT_CFG_KEYS, LOGGER, colorstr, yaml_load
from ultralytics.yolo.utils.checks import check_yaml
from ultralytics.yolo.utils.checks import check_requirements, check_yaml
from ultralytics.yolo.utils.torch_utils import (fuse_conv_and_bn, initialize_weights, intersect_dicts, make_divisible,
model_info, scale_img, time_sync)

Expand Down Expand Up @@ -357,7 +357,16 @@ def attempt_load_one_weight(weight, device=None, inplace=True, fuse=False):
# Loads a single model weights
from ultralytics.yolo.utils.downloads import attempt_download

ckpt = torch.load(attempt_download(weight), map_location='cpu') # load
weight = attempt_download(weight)
try:
ckpt = torch.load(weight, map_location='cpu') # load
except ModuleNotFoundError:
LOGGER.warning(f"WARNING ⚠️ {weight} is deprecated as it requires omegaconf, which is now removed from "
"ultralytics requirements.\nAutoInstall will occur now but this feature will be removed for "
"omegaconf models in the future.\nPlease train a new model or download updated models "
"from https://github.com/ultralytics/assets/releases/tag/v0.0.0")
check_requirements('omegaconf')
ckpt = torch.load(weight, map_location='cpu') # load
args = {**DEFAULT_CFG_DICT, **ckpt['train_args']} # combine model and default args, preferring model args
model = (ckpt.get('ema') or ckpt['model']).to(device).float() # FP32 model

Expand Down
45 changes: 40 additions & 5 deletions ultralytics/yolo/cfg/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@
from difflib import get_close_matches
from pathlib import Path
from types import SimpleNamespace
from typing import Dict, Union
from typing import Dict, List, Union

from ultralytics import __version__, yolo
from ultralytics.yolo.utils import (DEFAULT_CFG_DICT, DEFAULT_CFG_PATH, LOGGER, PREFIX, USER_CONFIG_DIR,
IterableSimpleNamespace, checks, colorstr, yaml_load, yaml_print)
IterableSimpleNamespace, colorstr, yaml_load, yaml_print)
from ultralytics.yolo.utils.checks import check_yolo

CLI_HELP_MSG = \
"""
Expand Down Expand Up @@ -111,6 +112,33 @@ def check_cfg_mismatch(base: Dict, custom: Dict):
sys.exit()


def merge_equals_args(args: List[str]) -> List[str]:
"""
Merges arguments around isolated '=' args in a list of strings.
The function considers cases where the first argument ends with '=' or the second starts with '=',
as well as when the middle one is an equals sign.
Args:
args (List[str]): A list of strings where each element is an argument.
Returns:
List[str]: A list of strings where the arguments around isolated '=' are merged.
"""
new_args = []
for i, arg in enumerate(args):
if arg == '=' and 0 < i < len(args) - 1:
new_args[-1] += f"={args[i + 1]}"
del args[i + 1]
elif arg.endswith('=') and i < len(args) - 1:
new_args.append(f"{arg}{args[i + 1]}")
del args[i + 1]
elif arg.startswith('=') and i > 0:
new_args[-1] += arg
else:
new_args.append(arg)
return new_args


def argument_error(arg):
return SyntaxError(f"'{arg}' is not a valid YOLO argument.\n{CLI_HELP_MSG}")

Expand All @@ -130,7 +158,7 @@ def entrypoint(debug=False):
It uses the package's default cfg and initializes it using the passed overrides.
Then it calls the CLI function with the composed cfg
"""
args = ['train', 'predict', 'model=yolov8n.pt'] if debug else sys.argv[1:]
args = ['train', 'model=yolov8n.pt', 'data=coco128.yaml', 'imgsz=32', 'epochs=1'] if debug else sys.argv[1:]
if not args: # no arguments passed
LOGGER.info(CLI_HELP_MSG)
return
Expand All @@ -139,14 +167,14 @@ def entrypoint(debug=False):
modes = 'train', 'val', 'predict', 'export'
special = {
'help': lambda: LOGGER.info(CLI_HELP_MSG),
'checks': checks.check_yolo,
'checks': check_yolo,
'version': lambda: LOGGER.info(__version__),
'settings': lambda: yaml_print(USER_CONFIG_DIR / 'settings.yaml'),
'cfg': lambda: yaml_print(DEFAULT_CFG_PATH),
'copy-cfg': copy_default_config}

overrides = {} # basic overrides, i.e. imgsz=320
for a in args:
for a in merge_equals_args(args): # merge spaces around '=' sign
if '=' in a:
try:
re.sub(r' *= *', '=', a) # remove spaces around equals sign
Expand Down Expand Up @@ -185,6 +213,13 @@ def entrypoint(debug=False):

cfg = get_cfg(DEFAULT_CFG_DICT, overrides) # create CFG instance

# Checks error catch
if cfg.mode == 'checks':
LOGGER.warning(
"WARNING ⚠️ 'yolo mode=checks' is deprecated and will be removed in the future. Use 'yolo checks' instead.")
check_yolo()
return

# Mapping from task to module
module = {"detect": yolo.v8.detect, "segment": yolo.v8.segment, "classify": yolo.v8.classify}.get(cfg.task)
if not module:
Expand Down
2 changes: 1 addition & 1 deletion ultralytics/yolo/data/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ def check_dataset_yaml(dataset, autodownload=True):
if s and autodownload:
LOGGER.warning(msg)
else:
raise FileNotFoundError(s)
raise FileNotFoundError(msg)
t = time.time()
if s.startswith('http') and s.endswith('.zip'): # URL
f = Path(s).name # filename
Expand Down
1 change: 0 additions & 1 deletion ultralytics/yolo/engine/trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,6 @@ def final_eval(self):
strip_optimizer(f) # strip optimizers
if f is self.best:
self.console.info(f'\nValidating {f}...')
self.validator.args.save_json = True
self.metrics = self.validator(model=f)
self.metrics.pop('fitness', None)
self.run_callbacks('on_fit_epoch_end')
Expand Down
Loading

0 comments on commit d6a4ffb

Please sign in to comment.