Update Tracker docstrings (#15469)
Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com> Co-authored-by: UltralyticsAssistant <web@ultralytics.com>
This commit is contained in:
parent
da2797a182
commit
b7c5db94b4
10 changed files with 501 additions and 196 deletions
|
|
@ -11,19 +11,44 @@ from pathlib import Path
|
|||
|
||||
|
||||
class WorkingDirectory(contextlib.ContextDecorator):
|
||||
"""Usage: @WorkingDirectory(dir) decorator or 'with WorkingDirectory(dir):' context manager."""
|
||||
"""
|
||||
A context manager and decorator for temporarily changing the working directory.
|
||||
|
||||
This class allows for the temporary change of the working directory using a context manager or decorator.
|
||||
It ensures that the original working directory is restored after the context or decorated function completes.
|
||||
|
||||
Attributes:
|
||||
dir (Path): The new directory to switch to.
|
||||
cwd (Path): The original current working directory before the switch.
|
||||
|
||||
Methods:
|
||||
__enter__: Changes the current directory to the specified directory.
|
||||
__exit__: Restores the original working directory on context exit.
|
||||
|
||||
Examples:
|
||||
Using as a context manager:
|
||||
>>> with WorkingDirectory('/path/to/new/dir'):
|
||||
>>> # Perform operations in the new directory
|
||||
>>> pass
|
||||
|
||||
Using as a decorator:
|
||||
>>> @WorkingDirectory('/path/to/new/dir')
|
||||
>>> def some_function():
|
||||
>>> # Perform operations in the new directory
|
||||
>>> pass
|
||||
"""
|
||||
|
||||
def __init__(self, new_dir):
|
||||
"""Sets the working directory to 'new_dir' upon instantiation."""
|
||||
"""Sets the working directory to 'new_dir' upon instantiation for use with context managers or decorators."""
|
||||
self.dir = new_dir # new dir
|
||||
self.cwd = Path.cwd().resolve() # current dir
|
||||
|
||||
def __enter__(self):
|
||||
"""Changes the current directory to the specified directory."""
|
||||
"""Changes the current working directory to the specified directory upon entering the context."""
|
||||
os.chdir(self.dir)
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb): # noqa
|
||||
"""Restore the current working directory on context exit."""
|
||||
"""Restores the original working directory when exiting the context."""
|
||||
os.chdir(self.cwd)
|
||||
|
||||
|
||||
|
|
@ -35,18 +60,16 @@ def spaces_in_path(path):
|
|||
file/directory back to its original location.
|
||||
|
||||
Args:
|
||||
path (str | Path): The original path.
|
||||
path (str | Path): The original path that may contain spaces.
|
||||
|
||||
Yields:
|
||||
(Path): Temporary path with spaces replaced by underscores if spaces were present, otherwise the original path.
|
||||
|
||||
Example:
|
||||
```python
|
||||
with ultralytics.utils.files import spaces_in_path
|
||||
|
||||
with spaces_in_path('/path/with spaces') as new_path:
|
||||
# Your code here
|
||||
```
|
||||
Examples:
|
||||
Use the context manager to handle paths with spaces:
|
||||
>>> from ultralytics.utils.files import spaces_in_path
|
||||
>>> with spaces_in_path('/path/with spaces') as new_path:
|
||||
>>> # Your code here
|
||||
"""
|
||||
|
||||
# If path has spaces, replace them with underscores
|
||||
|
|
@ -84,21 +107,35 @@ def spaces_in_path(path):
|
|||
|
||||
def increment_path(path, exist_ok=False, sep="", mkdir=False):
|
||||
"""
|
||||
Increments a file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.
|
||||
Increments a file or directory path, i.e., runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.
|
||||
|
||||
If the path exists and exist_ok is not set to True, the path will be incremented by appending a number and sep to
|
||||
If the path exists and `exist_ok` is not True, the path will be incremented by appending a number and `sep` to
|
||||
the end of the path. If the path is a file, the file extension will be preserved. If the path is a directory, the
|
||||
number will be appended directly to the end of the path. If mkdir is set to True, the path will be created as a
|
||||
number will be appended directly to the end of the path. If `mkdir` is set to True, the path will be created as a
|
||||
directory if it does not already exist.
|
||||
|
||||
Args:
|
||||
path (str, pathlib.Path): Path to increment.
|
||||
exist_ok (bool, optional): If True, the path will not be incremented and returned as-is. Defaults to False.
|
||||
sep (str, optional): Separator to use between the path and the incrementation number. Defaults to ''.
|
||||
mkdir (bool, optional): Create a directory if it does not exist. Defaults to False.
|
||||
path (str | pathlib.Path): Path to increment.
|
||||
exist_ok (bool): If True, the path will not be incremented and returned as-is.
|
||||
sep (str): Separator to use between the path and the incrementation number.
|
||||
mkdir (bool): Create a directory if it does not exist.
|
||||
|
||||
Returns:
|
||||
(pathlib.Path): Incremented path.
|
||||
|
||||
Examples:
|
||||
Increment a directory path:
|
||||
>>> from pathlib import Path
|
||||
>>> path = Path("runs/exp")
|
||||
>>> new_path = increment_path(path)
|
||||
>>> print(new_path)
|
||||
runs/exp2
|
||||
|
||||
Increment a file path:
|
||||
>>> path = Path("runs/exp/results.txt")
|
||||
>>> new_path = increment_path(path)
|
||||
>>> print(new_path)
|
||||
runs/exp/results2.txt
|
||||
"""
|
||||
path = Path(path) # os-agnostic
|
||||
if path.exists() and not exist_ok:
|
||||
|
|
@ -118,19 +155,19 @@ def increment_path(path, exist_ok=False, sep="", mkdir=False):
|
|||
|
||||
|
||||
def file_age(path=__file__):
|
||||
"""Return days since last file update."""
|
||||
"""Return days since the last modification of the specified file."""
|
||||
dt = datetime.now() - datetime.fromtimestamp(Path(path).stat().st_mtime) # delta
|
||||
return dt.days # + dt.seconds / 86400 # fractional days
|
||||
|
||||
|
||||
def file_date(path=__file__):
|
||||
"""Return human-readable file modification date, i.e. '2021-3-26'."""
|
||||
"""Returns the file modification date in 'YYYY-M-D' format."""
|
||||
t = datetime.fromtimestamp(Path(path).stat().st_mtime)
|
||||
return f"{t.year}-{t.month}-{t.day}"
|
||||
|
||||
|
||||
def file_size(path):
|
||||
"""Return file/dir size (MB)."""
|
||||
"""Returns the size of a file or directory in megabytes (MB)."""
|
||||
if isinstance(path, (str, Path)):
|
||||
mb = 1 << 20 # bytes to MiB (1024 ** 2)
|
||||
path = Path(path)
|
||||
|
|
@ -142,7 +179,7 @@ def file_size(path):
|
|||
|
||||
|
||||
def get_latest_run(search_dir="."):
|
||||
"""Return path to most recent 'last.pt' in /runs (i.e. to --resume from)."""
|
||||
"""Returns the path to the most recent 'last.pt' file in the specified directory for resuming training."""
|
||||
last_list = glob.glob(f"{search_dir}/**/last*.pt", recursive=True)
|
||||
return max(last_list, key=os.path.getctime) if last_list else ""
|
||||
|
||||
|
|
@ -152,17 +189,15 @@ def update_models(model_names=("yolov8n.pt",), source_dir=Path("."), update_name
|
|||
Updates and re-saves specified YOLO models in an 'updated_models' subdirectory.
|
||||
|
||||
Args:
|
||||
model_names (tuple, optional): Model filenames to update, defaults to ("yolov8n.pt").
|
||||
source_dir (Path, optional): Directory containing models and target subdirectory, defaults to current directory.
|
||||
update_names (bool, optional): Update model names from a data YAML.
|
||||
model_names (Tuple[str, ...]): Model filenames to update.
|
||||
source_dir (Path): Directory containing models and target subdirectory.
|
||||
update_names (bool): Update model names from a data YAML.
|
||||
|
||||
Example:
|
||||
```python
|
||||
from ultralytics.utils.files import update_models
|
||||
|
||||
model_names = (f"rtdetr-{size}.pt" for size in "lx")
|
||||
update_models(model_names)
|
||||
```
|
||||
Examples:
|
||||
Update specified YOLO models and save them in 'updated_models' subdirectory:
|
||||
>>> from ultralytics.utils.files import update_models
|
||||
>>> model_names = ("yolov8n.pt", "yolov8s.pt")
|
||||
>>> update_models(model_names, source_dir=Path("/models"), update_names=True)
|
||||
"""
|
||||
from ultralytics import YOLO
|
||||
from ultralytics.nn.autobackend import default_class_names
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue