Ruff format docstring Python code (#15792)

Signed-off-by: UltralyticsAssistant <web@ultralytics.com>
Co-authored-by: UltralyticsAssistant <web@ultralytics.com>
This commit is contained in:
Glenn Jocher 2024-08-25 01:08:07 +08:00 committed by GitHub
parent c1882a4327
commit d27664216b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
63 changed files with 370 additions and 374 deletions

View file

@ -765,8 +765,8 @@ def remove_colorstr(input_string):
(str): A new string with all ANSI escape codes removed.
Examples:
>>> remove_colorstr(colorstr('blue', 'bold', 'hello world'))
>>> 'hello world'
>>> remove_colorstr(colorstr("blue", "bold", "hello world"))
>>> "hello world"
"""
ansi_escape = re.compile(r"\x1B\[[0-9;]*[A-Za-z]")
return ansi_escape.sub("", input_string)
@ -780,12 +780,12 @@ class TryExcept(contextlib.ContextDecorator):
As a decorator:
>>> @TryExcept(msg="Error occurred in func", verbose=True)
>>> def func():
>>> # Function logic here
>>> # Function logic here
>>> pass
As a context manager:
>>> with TryExcept(msg="Error occurred in block", verbose=True):
>>> # Code block here
>>> # Code block here
>>> pass
"""
@ -816,7 +816,7 @@ class Retry(contextlib.ContextDecorator):
Example usage as a decorator:
>>> @Retry(times=3, delay=2)
>>> def test_func():
>>> # Replace with function logic that may raise exceptions
>>> # Replace with function logic that may raise exceptions
>>> return True
"""

View file

@ -71,7 +71,7 @@ def benchmark(
```python
from ultralytics.utils.benchmarks import benchmark
benchmark(model='yolov8n.pt', imgsz=640)
benchmark(model="yolov8n.pt", imgsz=640)
```
"""
import pandas as pd # scope for faster 'import ultralytics'
@ -302,7 +302,7 @@ class ProfileModels:
```python
from ultralytics.utils.benchmarks import ProfileModels
ProfileModels(['yolov8n.yaml', 'yolov8s.yaml'], imgsz=640).profile()
ProfileModels(["yolov8n.yaml", "yolov8s.yaml"], imgsz=640).profile()
```
"""

View file

@ -62,7 +62,7 @@ def parse_requirements(file_path=ROOT.parent / "requirements.txt", package=""):
```python
from ultralytics.utils.checks import parse_requirements
parse_requirements(package='ultralytics')
parse_requirements(package="ultralytics")
```
"""
@ -197,16 +197,16 @@ def check_version(
Example:
```python
# Check if current version is exactly 22.04
check_version(current='22.04', required='==22.04')
check_version(current="22.04", required="==22.04")
# Check if current version is greater than or equal to 22.04
check_version(current='22.10', required='22.04') # assumes '>=' inequality if none passed
check_version(current="22.10", required="22.04") # assumes '>=' inequality if none passed
# Check if current version is less than or equal to 22.04
check_version(current='22.04', required='<=22.04')
check_version(current="22.04", required="<=22.04")
# Check if current version is between 20.04 (inclusive) and 22.04 (exclusive)
check_version(current='21.10', required='>20.04,<22.04')
check_version(current="21.10", required=">20.04,<22.04")
```
"""
if not current: # if current is '' or None
@ -353,13 +353,13 @@ def check_requirements(requirements=ROOT.parent / "requirements.txt", exclude=()
from ultralytics.utils.checks import check_requirements
# Check a requirements.txt file
check_requirements('path/to/requirements.txt')
check_requirements("path/to/requirements.txt")
# Check a single package
check_requirements('ultralytics>=8.0.0')
check_requirements("ultralytics>=8.0.0")
# Check multiple packages
check_requirements(['numpy', 'ultralytics>=8.0.0'])
check_requirements(["numpy", "ultralytics>=8.0.0"])
```
"""
@ -634,7 +634,7 @@ def check_amp(model):
from ultralytics import YOLO
from ultralytics.utils.checks import check_amp
model = YOLO('yolov8n.pt').model.cuda()
model = YOLO("yolov8n.pt").model.cuda()
check_amp(model)
```

View file

@ -75,7 +75,7 @@ def delete_dsstore(path, files_to_delete=(".DS_Store", "__MACOSX")):
```python
from ultralytics.utils.downloads import delete_dsstore
delete_dsstore('path/to/dir')
delete_dsstore("path/to/dir")
```
Note:
@ -107,7 +107,7 @@ def zip_directory(directory, compress=True, exclude=(".DS_Store", "__MACOSX"), p
```python
from ultralytics.utils.downloads import zip_directory
file = zip_directory('path/to/dir')
file = zip_directory("path/to/dir")
```
"""
from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile
@ -153,7 +153,7 @@ def unzip_file(file, path=None, exclude=(".DS_Store", "__MACOSX"), exist_ok=Fals
```python
from ultralytics.utils.downloads import unzip_file
dir = unzip_file('path/to/file.zip')
dir = unzip_file("path/to/file.zip")
```
"""
from zipfile import BadZipFile, ZipFile, is_zipfile
@ -392,7 +392,7 @@ def get_github_assets(repo="ultralytics/assets", version="latest", retry=False):
Example:
```python
tag, assets = get_github_assets(repo='ultralytics/assets', version='latest')
tag, assets = get_github_assets(repo="ultralytics/assets", version="latest")
```
"""
@ -425,7 +425,7 @@ def attempt_download_asset(file, repo="ultralytics/assets", release="v8.2.0", **
Example:
```python
file_path = attempt_download_asset('yolov8n.pt', repo='ultralytics/assets', release='latest')
file_path = attempt_download_asset("yolov8n.pt", repo="ultralytics/assets", release="latest")
```
"""
from ultralytics.utils import SETTINGS # scoped for circular import
@ -480,7 +480,7 @@ def download(url, dir=Path.cwd(), unzip=True, delete=False, curl=False, threads=
Example:
```python
download('https://ultralytics.com/assets/example.zip', dir='path/to/dir', unzip=True)
download("https://ultralytics.com/assets/example.zip", dir="path/to/dir", unzip=True)
```
"""
dir = Path(dir)

View file

@ -28,13 +28,13 @@ class WorkingDirectory(contextlib.ContextDecorator):
Examples:
Using as a context manager:
>>> with WorkingDirectory('/path/to/new/dir'):
>>> # Perform operations in the new directory
>>> # 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
>>> # Perform operations in the new directory
>>> pass
"""
@ -69,7 +69,7 @@ def spaces_in_path(path):
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
>>> # Your code here
"""
# If path has spaces, replace them with underscores

View file

@ -199,7 +199,7 @@ class Instances:
instances = Instances(
bboxes=np.array([[10, 10, 30, 30], [20, 20, 40, 40]]),
segments=[np.array([[5, 5], [10, 10]]), np.array([[15, 15], [20, 20]])],
keypoints=np.array([[[5, 5, 1], [10, 10, 1]], [[15, 15, 1], [20, 20, 1]]])
keypoints=np.array([[[5, 5, 1], [10, 10, 1]], [[15, 15, 1], [20, 20, 1]]]),
)
```

View file

@ -902,8 +902,8 @@ def save_one_box(xyxy, im, file=Path("im.jpg"), gain=1.02, pad=10, square=False,
from ultralytics.utils.plotting import save_one_box
xyxy = [50, 50, 150, 150]
im = cv2.imread('image.jpg')
cropped_im = save_one_box(xyxy, im, file='cropped.jpg', square=True)
im = cv2.imread("image.jpg")
cropped_im = save_one_box(xyxy, im, file="cropped.jpg", square=True)
```
"""
@ -1109,7 +1109,7 @@ def plot_results(file="path/to/results.csv", dir="", segment=False, pose=False,
```python
from ultralytics.utils.plotting import plot_results
plot_results('path/to/results.csv', segment=True)
plot_results("path/to/results.csv", segment=True)
```
"""
import pandas as pd # scope for faster 'import ultralytics'
@ -1195,7 +1195,7 @@ def plot_tune_results(csv_file="tune_results.csv"):
csv_file (str, optional): Path to the CSV file containing the tuning results. Defaults to 'tune_results.csv'.
Examples:
>>> plot_tune_results('path/to/tune_results.csv')
>>> plot_tune_results("path/to/tune_results.csv")
"""
import pandas as pd # scope for faster 'import ultralytics'

View file

@ -137,10 +137,10 @@ def select_device(device="", batch=0, newline=False, verbose=True):
devices when using multiple GPUs.
Examples:
>>> select_device('cuda:0')
>>> select_device("cuda:0")
device(type='cuda', index=0)
>>> select_device('cpu')
>>> select_device("cpu")
device(type='cpu')
Note:
@ -331,11 +331,13 @@ def model_info_for_loggers(trainer):
Example:
YOLOv8n info for loggers
```python
results = {'model/parameters': 3151904,
'model/GFLOPs': 8.746,
'model/speed_ONNX(ms)': 41.244,
'model/speed_TensorRT(ms)': 3.211,
'model/speed_PyTorch(ms)': 18.755}
results = {
"model/parameters": 3151904,
"model/GFLOPs": 8.746,
"model/speed_ONNX(ms)": 41.244,
"model/speed_TensorRT(ms)": 3.211,
"model/speed_PyTorch(ms)": 18.755,
}
```
"""
if trainer.args.profile: # profile ONNX and TensorRT times
@ -542,7 +544,7 @@ def strip_optimizer(f: Union[str, Path] = "best.pt", s: str = "") -> None:
from pathlib import Path
from ultralytics.utils.torch_utils import strip_optimizer
for f in Path('path/to/model/checkpoints').rglob('*.pt'):
for f in Path("path/to/model/checkpoints").rglob("*.pt"):
strip_optimizer(f)
```

View file

@ -28,10 +28,10 @@ def run_ray_tune(
from ultralytics import YOLO
# Load a YOLOv8n model
model = YOLO('yolov8n.pt')
model = YOLO("yolov8n.pt")
# Start tuning hyperparameters for YOLOv8n training on the COCO8 dataset
result_grid = model.tune(data='coco8.yaml', use_ray=True)
result_grid = model.tune(data="coco8.yaml", use_ray=True)
```
"""