Merge pull request #1526 from roboflow/formatting/ruff-rules

refactor:  ruff rules enabled and fixed and code refactor made
This commit is contained in:
LinasKo 2024-09-19 21:18:09 +03:00 committed by GitHub
commit e3eeb5f2cc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 36 additions and 35 deletions

2
demo.ipynb vendored
View File

@ -1357,7 +1357,7 @@
}
],
"source": [
"IMAGE_NAME = list(ds.images.keys())[0]\n",
"IMAGE_NAME = next(iter(ds.images.keys()))\n",
"\n",
"image = ds.images[IMAGE_NAME]\n",
"annotations = ds.annotations[IMAGE_NAME]\n",

View File

@ -1,6 +1,6 @@
import argparse
import os
from typing import Dict, Iterable, List, Set
from typing import Dict, Iterable, List, Optional, Set
import cv2
import numpy as np
@ -77,7 +77,7 @@ class VideoProcessor:
roboflow_api_key: str,
model_id: str,
source_video_path: str,
target_video_path: str = None,
target_video_path: Optional[str] = None,
confidence_threshold: float = 0.3,
iou_threshold: float = 0.7,
) -> None:

View File

@ -1,5 +1,5 @@
import argparse
from typing import Dict, Iterable, List, Set
from typing import Dict, Iterable, List, Optional, Set
import cv2
import numpy as np
@ -74,7 +74,7 @@ class VideoProcessor:
self,
source_weights_path: str,
source_video_path: str,
target_video_path: str = None,
target_video_path: Optional[str] = None,
confidence_threshold: float = 0.3,
iou_threshold: float = 0.7,
) -> None:

View File

@ -146,7 +146,7 @@ indent-width = 4
[tool.ruff.lint]
# Enable pycodestyle (`E`) and Pyflakes (`F`) codes by default.
select = ["E", "F", "I", "A", "Q", "W"]
select = ["E", "F", "I", "A", "Q", "W","RUF"]
ignore = []
# Allow autofix for all enabled rules (when `--fix`) is provided.
fixable = [

View File

@ -249,7 +249,7 @@ class Detections:
results = model(image)[0]
detections = sv.Detections.from_ultralytics(results)
```
""" # noqa: E501 // docs
"""
if hasattr(ultralytics_results, "obb") and ultralytics_results.obb is not None:
class_id = ultralytics_results.obb.cls.cpu().numpy().astype(int)
@ -356,7 +356,7 @@ class Detections:
result = model(img)
detections = sv.Detections.from_tensorflow(result)
```
""" # noqa: E501 // docs
"""
boxes = tensorflow_results["detection_boxes"][0].numpy()
boxes[:, [0, 2]] *= resolution_wh[0]
@ -431,7 +431,7 @@ class Detections:
result = inference_detector(model, image)
detections = sv.Detections.from_mmdetection(result)
```
""" # noqa: E501 // docs
"""
return cls(
xyxy=mmdet_results.pred_instances.bboxes.cpu().numpy(),
@ -490,7 +490,7 @@ class Detections:
id2label=model.config.id2label
)
```
""" # noqa: E501 // docs
"""
if (
transformers_results.__class__.__name__ == "Tensor"

View File

@ -55,7 +55,7 @@ class LineZone:
line_zone.in_count, line_zone.out_count
# 7, 2
```
""" # noqa: E501 // docs
"""
def __init__(
self,

View File

@ -113,7 +113,7 @@ def from_florence_2(
oriented bounding boxes.
"""
assert len(result) == 1, f"Expected result with a single element. Got: {result}"
task = list(result.keys())[0]
task = next(iter(result.keys()))
if task not in SUPPORTED_TASKS_FLORENCE_2:
raise ValueError(
f"{task} not supported. Supported tasks are: {SUPPORTED_TASKS_FLORENCE_2}"

View File

@ -183,7 +183,7 @@ def group_overlapping_boxes(
ious = ious.flatten()
above_threshold = ious >= iou_threshold
merge_group = [idx] + np.flip(order[above_threshold]).tolist()
merge_group = [idx, *np.flip(order[above_threshold]).tolist()]
merge_groups.append(merge_group)
order = order[~above_threshold]
return merge_groups

View File

@ -48,7 +48,7 @@ class CSVSink:
detections = sv.Detections.from_ultralytics(result)
sink.append(detections, custom_data={'<CUSTOM_LABEL>':'<CUSTOM_DATA>'})
```
""" # noqa: E501 // docs
"""
def __init__(self, file_name: str = "output.csv") -> None:
"""
@ -104,7 +104,7 @@ class CSVSink:
@staticmethod
def parse_detection_data(
detections: Detections, custom_data: Dict[str, Any] = None
detections: Detections, custom_data: Optional[Dict[str, Any]] = None
) -> List[Dict[str, Any]]:
parsed_rows = []
for i in range(len(detections.xyxy)):
@ -137,7 +137,7 @@ class CSVSink:
return parsed_rows
def append(
self, detections: Detections, custom_data: Dict[str, Any] = None
self, detections: Detections, custom_data: Optional[Dict[str, Any]] = None
) -> None:
"""
Append detection data to the CSV file.

View File

@ -38,7 +38,7 @@ class JSONSink:
detections = sv.Detections.from_ultralytics(result)
sink.append(detections, custom_data={'<CUSTOM_LABEL>':'<CUSTOM_DATA>'})
```
""" # noqa: E501 // docs
"""
def __init__(self, file_name: str = "output.json") -> None:
"""
@ -92,7 +92,7 @@ class JSONSink:
@staticmethod
def parse_detection_data(
detections: Detections, custom_data: Dict[str, Any] = None
detections: Detections, custom_data: Optional[Dict[str, Any]] = None
) -> List[Dict[str, Any]]:
parsed_rows = []
for i in range(len(detections.xyxy)):
@ -126,7 +126,7 @@ class JSONSink:
return parsed_rows
def append(
self, detections: Detections, custom_data: Dict[str, Any] = None
self, detections: Detections, custom_data: Optional[Dict[str, Any]] = None
) -> None:
"""
Append detection data to the JSON file.

View File

@ -53,7 +53,7 @@ class DetectionsSmoother:
annotated_frame = box_annotator.annotate(frame.copy(), detections)
sink.write_frame(annotated_frame)
```
""" # noqa: E501 // docs
"""
def __init__(self, length: int = 5) -> None:
"""

View File

@ -429,7 +429,7 @@ class KeyPoints:
results = model.predict(image, conf=0.1)
key_points = sv.KeyPoints.from_yolo_nas(results)
```
""" # noqa: E501 // docs
"""
if len(yolo_nas_results.prediction.poses) == 0:
return cls.empty()

View File

@ -1,11 +1,11 @@
from enum import Enum
from typing import Dict, List, Tuple
from typing import Dict, Tuple
Edges = List[Tuple[int, int]]
Edges = Tuple[Tuple[int, int], ...]
class Skeleton(Enum):
COCO = [
COCO: Edges = (
(1, 2),
(1, 3),
(2, 3),
@ -23,9 +23,9 @@ class Skeleton(Enum):
(15, 13),
(16, 14),
(17, 15),
]
)
GHUM = [
GHUM: Edges = (
(1, 2),
(1, 5),
(2, 3),
@ -61,9 +61,9 @@ class Skeleton(Enum):
(29, 33),
(30, 32),
(31, 33),
]
)
FACEMESH_TESSELATION_NO_IRIS = [
FACEMESH_TESSELATION_NO_IRIS: Edges = (
(128, 35),
(35, 140),
(140, 128),
@ -2620,9 +2620,9 @@ class Skeleton(Enum):
(340, 449),
(449, 256),
(256, 340),
]
)
FACEMESH_TESSELATION = [
FACEMESH_TESSELATION: Edges = (
(474, 474),
(475, 476),
(476, 477),
@ -2633,7 +2633,8 @@ class Skeleton(Enum):
(471, 472),
(472, 473),
(473, 470),
] + FACEMESH_TESSELATION_NO_IRIS
*FACEMESH_TESSELATION_NO_IRIS,
)
SKELETONS_BY_EDGE_COUNT: Dict[int, Edges] = {}

View File

@ -440,8 +440,8 @@ class ConfusionMatrix:
class_names = classes if classes is not None else self.classes
use_labels_for_ticks = class_names is not None and (0 < len(class_names) < 99)
if use_labels_for_ticks:
x_tick_labels = class_names + ["FN"]
y_tick_labels = class_names + ["FP"]
x_tick_labels = [*class_names, "FN"]
y_tick_labels = [*class_names, "FP"]
num_ticks = len(x_tick_labels)
else:
x_tick_labels = None

View File

@ -1,5 +1,5 @@
from contextlib import ExitStack as DoesNotRaise
from typing import Dict, List, Tuple, Union
from typing import Dict, List, Optional, Tuple, Union
import numpy as np
import pytest
@ -21,7 +21,7 @@ def mock_coco_annotation(
category_id: int = 0,
bbox: Tuple[float, float, float, float] = (0.0, 0.0, 0.0, 0.0),
area: float = 0.0,
segmentation: Union[List[list], Dict] = None,
segmentation: Optional[Union[List[list], Dict]] = None,
iscrowd: bool = False,
) -> dict:
if not segmentation: