From 30741add9de8d5bd6bc47a80b0831fc4fcb1fc6f Mon Sep 17 00:00:00 2001 From: Glenn Jocher Date: Sun, 31 Aug 2025 23:49:12 +0200 Subject: [PATCH] PEP8 refactor (#21890) Signed-off-by: Glenn Jocher Co-authored-by: UltralyticsAssistant --- docs/build_reference.py | 27 +++++++-------- .../interactive_tracker.py | 9 ++--- tests/test_cuda.py | 11 +++--- tests/test_exports.py | 7 +--- tests/test_solutions.py | 2 +- ultralytics/data/annotator.py | 3 +- ultralytics/data/augment.py | 4 +-- ultralytics/data/build.py | 4 +-- ultralytics/data/converter.py | 2 +- ultralytics/data/utils.py | 14 +++++--- ultralytics/engine/exporter.py | 4 +-- ultralytics/hub/session.py | 2 +- ultralytics/models/sam/modules/sam.py | 9 ++--- ultralytics/models/sam/predict.py | 15 ++++---- ultralytics/models/yolo/detect/predict.py | 2 +- ultralytics/nn/modules/head.py | 9 +++-- ultralytics/solutions/analytics.py | 6 ++-- ultralytics/solutions/streamlit_inference.py | 7 ++-- ultralytics/trackers/byte_tracker.py | 2 +- ultralytics/utils/__init__.py | 13 ++++--- ultralytics/utils/autodevice.py | 8 ++--- ultralytics/utils/metrics.py | 8 ++--- ultralytics/utils/plotting.py | 34 ++++++++++--------- ultralytics/utils/tqdm.py | 27 ++++++++------- 24 files changed, 118 insertions(+), 111 deletions(-) diff --git a/docs/build_reference.py b/docs/build_reference.py index 7cf4282b..f42d62c4 100644 --- a/docs/build_reference.py +++ b/docs/build_reference.py @@ -143,10 +143,11 @@ def update_mkdocs_file(reference_yaml: str) -> None: # Build new section with proper indentation new_section_lines = ["\n - Reference:"] - for line in reference_yaml.splitlines(): - if line.strip() == "- reference:": # Skip redundant header - continue - new_section_lines.append(f" {line}") + new_section_lines.extend( + f" {line}" + for line in reference_yaml.splitlines() + if line.strip() != "- reference:" # Skip redundant header + ) new_ref_section = "\n".join(new_section_lines) + "\n" if ref_match: @@ -170,17 +171,15 @@ def update_mkdocs_file(reference_yaml: str) -> None: MKDOCS_YAML.write_text(new_content) subprocess.run(["npx", "prettier", "--write", str(MKDOCS_YAML)], check=False, cwd=PACKAGE_DIR.parent) print(f"Updated Reference section in {MKDOCS_YAML}") - else: + elif help_match := re.search(r"(\n - Help:)", mkdocs_content): # No existing Reference section, we need to add it - help_match = re.search(r"(\n - Help:)", mkdocs_content) - if help_match: - help_section = help_match.group(1) - # Insert before Help section - new_content = mkdocs_content.replace(help_section, f"{new_ref_section}{help_section}") - MKDOCS_YAML.write_text(new_content) - print(f"Added new Reference section before Help in {MKDOCS_YAML}") - else: - print("Could not find a suitable location to add Reference section") + help_section = help_match.group(1) + # Insert before Help section + new_content = mkdocs_content.replace(help_section, f"{new_ref_section}{help_section}") + MKDOCS_YAML.write_text(new_content) + print(f"Added new Reference section before Help in {MKDOCS_YAML}") + else: + print("Could not find a suitable location to add Reference section") def main(): diff --git a/examples/YOLO-Interactive-Tracking-UI/interactive_tracker.py b/examples/YOLO-Interactive-Tracking-UI/interactive_tracker.py index 0c518d44..6abf0015 100644 --- a/examples/YOLO-Interactive-Tracking-UI/interactive_tracker.py +++ b/examples/YOLO-Interactive-Tracking-UI/interactive_tracker.py @@ -87,13 +87,14 @@ def extend_line_from_edge(mid_x: int, mid_y: int, direction: str, img_shape: Tup h, w = img_shape[:2] if direction == "left": return 0, mid_y - if direction == "right": + elif direction == "right": return w - 1, mid_y - if direction == "up": + elif direction == "up": return mid_x, 0 - if direction == "down": + elif direction == "down": return mid_x, h - 1 - return mid_x, mid_y + else: + return mid_x, mid_y def draw_tracking_scope(im, bbox: tuple, color: tuple) -> None: diff --git a/tests/test_cuda.py b/tests/test_cuda.py index 2e11311b..300cad9c 100644 --- a/tests/test_cuda.py +++ b/tests/test_cuda.py @@ -23,10 +23,11 @@ if CUDA_IS_AVAILABLE: gpu_info = GPUInfo() gpu_info.print_status() autodevice_fraction = __import__("os").environ.get("YOLO_AUTODEVICE_FRACTION_FREE", 0.3) - idle_gpus = gpu_info.select_idle_gpu( - count=2, min_memory_fraction=autodevice_fraction, min_util_fraction=autodevice_fraction - ) - if idle_gpus: + if idle_gpus := gpu_info.select_idle_gpu( + count=2, + min_memory_fraction=autodevice_fraction, + min_util_fraction=autodevice_fraction, + ): DEVICES = idle_gpus @@ -112,9 +113,9 @@ def test_train(): import os device = tuple(DEVICES) if len(DEVICES) > 1 else DEVICES[0] - results = YOLO(MODEL).train(data="coco8.yaml", imgsz=64, epochs=1, device=device) # requires imgsz>=64 # NVIDIA Jetson only has one GPU and therefore skipping checks if not IS_JETSON: + results = YOLO(MODEL).train(data="coco8.yaml", imgsz=64, epochs=1, device=device) # requires imgsz>=64 visible = eval(os.environ["CUDA_VISIBLE_DEVICES"]) assert visible == device, f"Passed GPUs '{device}', but used GPUs '{visible}'" assert ( diff --git a/tests/test_exports.py b/tests/test_exports.py index a06f73af..9e834be1 100644 --- a/tests/test_exports.py +++ b/tests/test_exports.py @@ -241,12 +241,7 @@ def test_export_ncnn(): @pytest.mark.slow -@pytest.mark.parametrize( - "task, half, batch", - [ # generate all combinations except for exclusion cases - (task, half, batch) for task, half, batch in product(TASKS, [True, False], [1]) - ], -) +@pytest.mark.parametrize("task, half, batch", list(product(TASKS, [True, False], [1]))) def test_export_ncnn_matrix(task, half, batch): """Test YOLO export to NCNN format considering various export configurations.""" file = YOLO(TASK2MODEL[task]).export(format="ncnn", imgsz=32, half=half, batch=batch) diff --git a/tests/test_solutions.py b/tests/test_solutions.py index c2818cb5..64a77c7e 100644 --- a/tests/test_solutions.py +++ b/tests/test_solutions.py @@ -227,7 +227,7 @@ def test_right_click_reset(): dc = solutions.DistanceCalculation() dc.selected_boxes, dc.left_mouse_count = {1: [10, 10, 50, 50]}, 1 dc.mouse_event_for_distance(cv2.EVENT_RBUTTONDOWN, 0, 0, None, None) - assert dc.selected_boxes == {} + assert not dc.selected_boxes assert dc.left_mouse_count == 0 diff --git a/ultralytics/data/annotator.py b/ultralytics/data/annotator.py index a215ec20..c34613e8 100644 --- a/ultralytics/data/annotator.py +++ b/ultralytics/data/annotator.py @@ -54,8 +54,7 @@ def auto_annotate( ) for result in det_results: - class_ids = result.boxes.cls.int().tolist() # Extract class IDs from detection results - if class_ids: + if class_ids := result.boxes.cls.int().tolist(): # Extract class IDs from detection results boxes = result.boxes.xyxy # Boxes object for bbox outputs sam_results = sam_model(result.orig_img, bboxes=boxes, verbose=False, save=False, device=device) segments = sam_results[0].masks.xyn diff --git a/ultralytics/data/augment.py b/ultralytics/data/augment.py index 439bbda4..5aecdc34 100644 --- a/ultralytics/data/augment.py +++ b/ultralytics/data/augment.py @@ -587,7 +587,7 @@ class Mosaic(BaseMixTransform): >>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=4) >>> augmented_data = mosaic._mix_transform(labels) """ - assert labels.get("rect_shape", None) is None, "rect and mosaic are mutually exclusive." + assert labels.get("rect_shape") is None, "rect and mosaic are mutually exclusive." assert len(labels.get("mix_labels", [])), "There are no other images for mosaic augment." return ( self._mosaic3(labels) if self.n == 3 else self._mosaic4(labels) if self.n == 4 else self._mosaic9(labels) @@ -836,7 +836,7 @@ class Mosaic(BaseMixTransform): >>> print(result.keys()) dict_keys(['im_file', 'ori_shape', 'resized_shape', 'cls', 'instances', 'mosaic_border']) """ - if len(mosaic_labels) == 0: + if not mosaic_labels: return {} cls = [] instances = [] diff --git a/ultralytics/data/build.py b/ultralytics/data/build.py index 32a0943f..6a1884cd 100644 --- a/ultralytics/data/build.py +++ b/ultralytics/data/build.py @@ -133,7 +133,7 @@ def build_yolo_dataset( rect=cfg.rect or rect, # rectangular batches cache=cfg.cache or None, single_cls=cfg.single_cls or False, - stride=int(stride), + stride=stride, pad=0.0 if mode == "train" else 0.5, prefix=colorstr(f"{mode}: "), task=cfg.task, @@ -165,7 +165,7 @@ def build_grounding( rect=cfg.rect or rect, # rectangular batches cache=cfg.cache or None, single_cls=cfg.single_cls or False, - stride=int(stride), + stride=stride, pad=0.0 if mode == "train" else 0.5, prefix=colorstr(f"{mode}: "), task=cfg.task, diff --git a/ultralytics/data/converter.py b/ultralytics/data/converter.py index 0c6ee911..4fb934fe 100644 --- a/ultralytics/data/converter.py +++ b/ultralytics/data/converter.py @@ -733,7 +733,7 @@ def convert_to_multispectral(path: Union[str, Path], n_channels: int = 10, repla path = Path(path) if path.is_dir(): # Process directory - im_files = sum([list(path.rglob(f"*.{ext}")) for ext in (IMG_FORMATS - {"tif", "tiff"})], []) + im_files = sum((list(path.rglob(f"*.{ext}")) for ext in (IMG_FORMATS - {"tif", "tiff"})), []) for im_path in im_files: try: convert_to_multispectral(im_path, n_channels) diff --git a/ultralytics/data/utils.py b/ultralytics/data/utils.py index 2557768d..81f43649 100644 --- a/ultralytics/data/utils.py +++ b/ultralytics/data/utils.py @@ -66,7 +66,7 @@ def check_file_speeds( >>> image_files = list(Path("dataset/images").glob("*.jpg")) >>> check_file_speeds(image_files, threshold_ms=15) """ - if not files or len(files) == 0: + if not files: LOGGER.warning(f"{prefix}Image speed checks: No files to check") return @@ -345,8 +345,13 @@ def polygons2masks_overlap( ) areas = [] ms = [] - for si in range(len(segments)): - mask = polygon2mask(imgsz, [segments[si].reshape(-1)], downsample_ratio=downsample_ratio, color=1) + for segment in segments: + mask = polygon2mask( + imgsz, + [segment.reshape(-1)], + downsample_ratio=downsample_ratio, + color=1, + ) ms.append(mask.astype(masks.dtype)) areas.append(mask.sum()) areas = np.asarray(areas) @@ -517,8 +522,7 @@ def check_cls_dataset(dataset: Union[str, Path], split: str = "") -> Dict[str, A train_set = data_dir / "train" if not train_set.is_dir(): LOGGER.warning(f"Dataset 'split=train' not found at {train_set}") - image_files = list(data_dir.rglob("*.jpg")) + list(data_dir.rglob("*.png")) - if image_files: + if image_files := list(data_dir.rglob("*.jpg")) + list(data_dir.rglob("*.png")): from ultralytics.data.split import split_classify_dataset LOGGER.info(f"Found {len(image_files)} images in subdirectories. Attempting to split...") diff --git a/ultralytics/engine/exporter.py b/ultralytics/engine/exporter.py index 9bb0581e..c6b618e2 100644 --- a/ultralytics/engine/exporter.py +++ b/ultralytics/engine/exporter.py @@ -349,7 +349,7 @@ class Exporter: assert not getattr(model, "end2end", False), "TFLite INT8 export not supported for end2end models." if self.args.nms: assert not isinstance(model, ClassificationModel), "'nms=True' is not valid for classification models." - assert not (tflite and ARM64 and LINUX), "TFLite export with NMS unsupported on ARM64 Linux" + assert not tflite or not ARM64 or not LINUX, "TFLite export with NMS unsupported on ARM64 Linux" if getattr(model, "end2end", False): LOGGER.warning("'nms=True' is not available for end2end models. Forcing 'nms=False'.") self.args.nms = False @@ -436,7 +436,7 @@ class Exporter: y = None for _ in range(2): # dry runs - y = NMSModel(model, self.args)(im) if self.args.nms and not (coreml or imx) else model(im) + y = NMSModel(model, self.args)(im) if self.args.nms and not coreml and not imx else model(im) if self.args.half and onnx and self.device.type != "cpu": im, model = im.half(), model.half() # to FP16 diff --git a/ultralytics/hub/session.py b/ultralytics/hub/session.py index 5d9547d3..0c391c1f 100644 --- a/ultralytics/hub/session.py +++ b/ultralytics/hub/session.py @@ -204,7 +204,7 @@ class HUBTrainingSession: HUBModelError: If the identifier format is not recognized. """ api_key, model_id, filename = None, None, None - if str(identifier).endswith((".pt", ".yaml")): + if identifier.endswith((".pt", ".yaml")): filename = identifier elif identifier.startswith(f"{HUB_WEB_ROOT}/models/"): parsed_url = urlparse(identifier) diff --git a/ultralytics/models/sam/modules/sam.py b/ultralytics/models/sam/modules/sam.py index ecca05ef..00ae7dd5 100644 --- a/ultralytics/models/sam/modules/sam.py +++ b/ultralytics/models/sam/modules/sam.py @@ -959,7 +959,6 @@ class SAM2Model(torch.nn.Module): prev_sam_mask_logits=None, ): """Perform a single tracking step, updating object masks and memory features based on current frame inputs.""" - current_out = {} sam_outputs, _, _ = self._track_step( frame_idx, is_init_cond_frame, @@ -975,9 +974,11 @@ class SAM2Model(torch.nn.Module): ) _, _, _, low_res_masks, high_res_masks, obj_ptr, object_score_logits = sam_outputs - current_out["pred_masks"] = low_res_masks - current_out["pred_masks_high_res"] = high_res_masks - current_out["obj_ptr"] = obj_ptr + current_out = { + "pred_masks": low_res_masks, + "pred_masks_high_res": high_res_masks, + "obj_ptr": obj_ptr, + } if not self.training: # Only add this in inference (to avoid unused param in activation checkpointing; # it's mainly used in the demo to encode spatial memories w/ consolidated masks) diff --git a/ultralytics/models/sam/predict.py b/ultralytics/models/sam/predict.py index d6f38742..b203d440 100644 --- a/ultralytics/models/sam/predict.py +++ b/ultralytics/models/sam/predict.py @@ -2010,7 +2010,6 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor): current_out (Dict[str, Any]): A dictionary containing the current output with mask predictions and object pointers. Keys include 'point_inputs', 'mask_inputs', 'pred_masks', 'pred_masks_high_res', 'obj_ptr', 'object_score_logits'. """ - current_out = {} if mask is not None and self.model.use_mask_input_as_output_without_sam: # When use_mask_input_as_output_without_sam=True, we directly output the mask input # (see it as a GT mask) without using a SAM prompt encoder + mask decoder. @@ -2021,7 +2020,7 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor): # fused the visual feature with previous memory features in the memory bank pix_feat_with_mem = self._prepare_memory_conditioned_features(obj_idx) # calculate the first feature if adding obj_idx exists(means adding prompts) - pix_feat_with_mem = pix_feat_with_mem[0:1] if obj_idx is not None else pix_feat_with_mem + pix_feat_with_mem = pix_feat_with_mem[:1] if obj_idx is not None else pix_feat_with_mem _, _, _, low_res_masks, high_res_masks, obj_ptr, object_score_logits = self.model._forward_sam_heads( backbone_features=pix_feat_with_mem, point_inputs={"point_coords": point, "point_labels": label} if obj_idx is not None else None, @@ -2029,9 +2028,9 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor): multimask_output=False, high_res_features=[feat[: pix_feat_with_mem.size(0)] for feat in self.high_res_features], ) - current_out["pred_masks"] = low_res_masks - current_out["pred_masks_high_res"] = high_res_masks - current_out["obj_ptr"] = obj_ptr - current_out["object_score_logits"] = object_score_logits - - return current_out + return { + "pred_masks": low_res_masks, + "pred_masks_high_res": high_res_masks, + "obj_ptr": obj_ptr, + "object_score_logits": object_score_logits, + } diff --git a/ultralytics/models/yolo/detect/predict.py b/ultralytics/models/yolo/detect/predict.py index 508d3d26..60ad3514 100644 --- a/ultralytics/models/yolo/detect/predict.py +++ b/ultralytics/models/yolo/detect/predict.py @@ -85,7 +85,7 @@ class DetectionPredictor(BasePredictor): """Extract object features from the feature maps.""" import torch - s = min([x.shape[1] for x in feat_maps]) # find smallest vector length + s = min(x.shape[1] for x in feat_maps) # find shortest vector length obj_feats = torch.cat( [x.permute(0, 2, 3, 1).reshape(x.shape[0], -1, s, x.shape[1] // s).mean(dim=-1) for x in feat_maps], dim=1 ) # mean reduce all vectors to same length diff --git a/ultralytics/nn/modules/head.py b/ultralytics/nn/modules/head.py index 2f2a97f5..4dda5b2c 100644 --- a/ultralytics/nn/modules/head.py +++ b/ultralytics/nn/modules/head.py @@ -200,7 +200,12 @@ class Detect(nn.Module): def decode_bboxes(self, bboxes: torch.Tensor, anchors: torch.Tensor, xywh: bool = True) -> torch.Tensor: """Decode bounding boxes from predictions.""" - return dist2bbox(bboxes, anchors, xywh=xywh and not (self.end2end or self.xyxy), dim=1) + return dist2bbox( + bboxes, + anchors, + xywh=xywh and not self.end2end and not self.xyxy, + dim=1, + ) @staticmethod def postprocess(preds: torch.Tensor, max_det: int, nc: int = 80) -> torch.Tensor: @@ -642,7 +647,7 @@ class YOLOEDetect(Detect): super().__init__(nc, ch) c3 = max(ch[0], min(self.nc, 100)) assert c3 <= embed - assert with_bn is True + assert with_bn self.cv3 = ( nn.ModuleList(nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, embed, 1)) for x in ch) if self.legacy diff --git a/ultralytics/solutions/analytics.py b/ultralytics/solutions/analytics.py index 51db6f22..0cea2221 100644 --- a/ultralytics/solutions/analytics.py +++ b/ultralytics/solutions/analytics.py @@ -204,7 +204,7 @@ class Analytics(BaseSolution): markersize=self.line_width * 5, label=f"{key} Data Points", ) - if plot == "bar": + elif plot == "bar": self.ax.clear() # clear bar data for label in labels: # Map labels to colors if label not in self.color_mapping: @@ -224,12 +224,12 @@ class Analytics(BaseSolution): for bar, label in zip(bars, labels): bar.set_label(label) # Assign label to each bar self.ax.legend(loc="upper left", fontsize=13, facecolor=self.fg_color, edgecolor=self.fg_color) - if plot == "pie": + elif plot == "pie": total = sum(counts) percentages = [size / total * 100 for size in counts] - start_angle = 90 self.ax.clear() + start_angle = 90 # Create pie chart and create legend labels with percentages wedges, _ = self.ax.pie( counts, labels=labels, startangle=start_angle, textprops={"color": self.fg_color}, autopct=None diff --git a/ultralytics/solutions/streamlit_inference.py b/ultralytics/solutions/streamlit_inference.py index 704172f1..84c7abeb 100644 --- a/ultralytics/solutions/streamlit_inference.py +++ b/ultralytics/solutions/streamlit_inference.py @@ -141,8 +141,9 @@ class Inference: elif self.source == "image": import tempfile # scope import - imgfiles = self.st.sidebar.file_uploader("Upload Image Files", type=IMG_FORMATS, accept_multiple_files=True) - if imgfiles: + if imgfiles := self.st.sidebar.file_uploader( + "Upload Image Files", type=IMG_FORMATS, accept_multiple_files=True + ): for imgfile in imgfiles: # Save each uploaded image to a temporary file with tempfile.NamedTemporaryFile(delete=False, suffix=f".{imgfile.name.split('.')[-1]}") as tf: tf.write(imgfile.read()) @@ -185,7 +186,7 @@ class Inference: def image_inference(self) -> None: """Perform inference on uploaded images.""" - for idx, img_info in enumerate(self.img_file_names): + for img_info in self.img_file_names: img_path = img_info["path"] image = cv2.imread(img_path) # Load and display the original image if image is not None: diff --git a/ultralytics/trackers/byte_tracker.py b/ultralytics/trackers/byte_tracker.py index ea7d178a..a16633fc 100644 --- a/ultralytics/trackers/byte_tracker.py +++ b/ultralytics/trackers/byte_tracker.py @@ -106,7 +106,7 @@ class STrack(BaseTrack): @staticmethod def multi_gmc(stracks: List["STrack"], H: np.ndarray = np.eye(2, 3)): """Update state tracks positions and covariances using a homography matrix for multiple tracks.""" - if len(stracks) > 0: + if stracks: multi_mean = np.asarray([st.mean.copy() for st in stracks]) multi_covariance = np.asarray([st.covariance for st in stracks]) diff --git a/ultralytics/utils/__init__.py b/ultralytics/utils/__init__.py index b64eaa03..14862f08 100644 --- a/ultralytics/utils/__init__.py +++ b/ultralytics/utils/__init__.py @@ -191,9 +191,10 @@ class DataExportMixin: def _to_str_simple(v): if v is None: return "" - if isinstance(v, (dict, list, tuple, set)): + elif isinstance(v, (dict, list, tuple, set)): return repr(v) - return str(v) + else: + return str(v) df_str = df.select( [pl.col(c).map_elements(_to_str_simple, return_dtype=pl.String).alias(c) for c in df.columns] @@ -415,10 +416,10 @@ def set_logging(name="LOGGING_NAME", verbose=True): """Format log records with prefixes based on level.""" # Apply prefixes based on log level if record.levelno == logging.WARNING: - prefix = "WARNING ⚠️" if not WINDOWS else "WARNING" + prefix = "WARNING" if WINDOWS else "WARNING ⚠️" record.msg = f"{prefix} {record.msg}" elif record.levelno == logging.ERROR: - prefix = "ERROR ❌" if not WINDOWS else "ERROR" + prefix = "ERROR" if WINDOWS else "ERROR ❌" record.msg = f"{prefix} {record.msg}" # Handle emojis in message based on platform @@ -429,7 +430,7 @@ def set_logging(name="LOGGING_NAME", verbose=True): # Handle Windows UTF-8 encoding issues if WINDOWS and hasattr(sys.stdout, "encoding") and sys.stdout.encoding != "utf-8": - try: + with contextlib.suppress(Exception): # Attempt to reconfigure stdout to use UTF-8 encoding if possible if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8") @@ -438,8 +439,6 @@ def set_logging(name="LOGGING_NAME", verbose=True): import io sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") - except Exception: - pass # Create and configure the StreamHandler with the appropriate formatter and level stream_handler = logging.StreamHandler(sys.stdout) diff --git a/ultralytics/utils/autodevice.py b/ultralytics/utils/autodevice.py index 7e25707f..d546a2c4 100644 --- a/ultralytics/utils/autodevice.py +++ b/ultralytics/utils/autodevice.py @@ -78,8 +78,7 @@ class GPUInfo: try: device_count = self.pynvml.nvmlDeviceGetCount() - for i in range(device_count): - self.gpu_stats.append(self._get_device_stats(i)) + self.gpu_stats.extend(self._get_device_stats(i) for i in range(device_count)) except Exception as e: LOGGER.warning(f"Error during device query: {e}") self.gpu_stats = [] @@ -195,12 +194,11 @@ if __name__ == "__main__": gpu_info = GPUInfo() gpu_info.print_status() - selected = gpu_info.select_idle_gpu( + if selected := gpu_info.select_idle_gpu( count=num_gpus_to_select, min_memory_fraction=required_free_mem_fraction, min_util_fraction=required_free_util_fraction, - ) - if selected: + ): print(f"\n==> Using selected GPU indices: {selected}") devices = [f"cuda:{idx}" for idx in selected] print(f" Target devices: {devices}") diff --git a/ultralytics/utils/metrics.py b/ultralytics/utils/metrics.py index d9a0286b..7c8956e8 100644 --- a/ultralytics/utils/metrics.py +++ b/ultralytics/utils/metrics.py @@ -404,7 +404,7 @@ class ConfusionMatrix(DataExportMixin): no_pred = len(detections["cls"]) == 0 if gt_cls.shape[0] == 0: # Check if labels is empty if not no_pred: - detections = {k: detections[k][detections["conf"] > conf] for k in detections.keys()} + detections = {k: detections[k][detections["conf"] > conf] for k in detections} detection_classes = detections["cls"].int().tolist() for i, dc in enumerate(detection_classes): self.matrix[dc, self.nc] += 1 # FP @@ -417,7 +417,7 @@ class ConfusionMatrix(DataExportMixin): self._append_matches("FN", batch, i) return - detections = {k: detections[k][detections["conf"] > conf] for k in detections.keys()} + detections = {k: detections[k][detections["conf"] > conf] for k in detections} gt_classes = gt_cls.int().tolist() detection_classes = detections["cls"].int().tolist() bboxes = detections["bboxes"] @@ -497,7 +497,7 @@ class ConfusionMatrix(DataExportMixin): labels[k] += mbatch[k] labels = {k: torch.stack(v, 0) if len(v) else v for k, v in labels.items()} - if not self.task == "obb" and len(labels["bboxes"]): + if self.task != "obb" and len(labels["bboxes"]): labels["bboxes"] = xyxy2xywh(labels["bboxes"]) (save_dir / "visualizations").mkdir(parents=True, exist_ok=True) plot_images( @@ -1097,7 +1097,7 @@ class DetMetrics(SimpleClass, DataExportMixin): (Dict[str, np.ndarray]): Dictionary containing concatenated statistics arrays. """ stats = {k: np.concatenate(v, 0) for k, v in self.stats.items()} # to numpy - if len(stats) == 0: + if not stats: return stats results = ap_per_class( stats["tp"], diff --git a/ultralytics/utils/plotting.py b/ultralytics/utils/plotting.py index 125459d2..cfd96023 100644 --- a/ultralytics/utils/plotting.py +++ b/ultralytics/utils/plotting.py @@ -1,9 +1,11 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +from __future__ import annotations + import math import warnings from pathlib import Path -from typing import Any, Callable, Dict, List, Optional, Union +from typing import Any, Callable import cv2 import numpy as np @@ -142,12 +144,12 @@ class Colors: dtype=np.uint8, ) - def __call__(self, i: int, bgr: bool = False) -> tuple: + def __call__(self, i: int | torch.Tensor, bgr: bool = False) -> tuple: """ Convert hex color codes to RGB values. Args: - i (int): Color index. + i (int | torch.Tensor): Color index. bgr (bool, optional): Whether to return BGR format instead of RGB. Returns: @@ -190,8 +192,8 @@ class Annotator: def __init__( self, im, - line_width: Optional[int] = None, - font_size: Optional[int] = None, + line_width: int | None = None, + font_size: int | None = None, font: str = "Arial.ttf", pil: bool = False, example: str = "abc", @@ -409,10 +411,10 @@ class Annotator: self, kpts, shape: tuple = (640, 640), - radius: Optional[int] = None, + radius: int | None = None, kpt_line: bool = True, conf_thres: float = 0.25, - kpt_color: Optional[tuple] = None, + kpt_color: tuple | None = None, ): """ Plot keypoints on the image. @@ -517,7 +519,7 @@ class Annotator: """Return annotated image as array.""" return np.asarray(self.im) - def show(self, title: Optional[str] = None): + def show(self, title: str | None = None): """Show the annotated image.""" im = Image.fromarray(np.asarray(self.im)[..., ::-1]) # Convert numpy array to PIL Image with RGB to BGR if IS_COLAB or IS_KAGGLE: # can not use IS_JUPYTER as will run for all ipython environments @@ -533,7 +535,7 @@ class Annotator: cv2.imwrite(filename, np.asarray(self.im)) @staticmethod - def get_bbox_dimension(bbox: Optional[tuple] = None): + def get_bbox_dimension(bbox: tuple | None = None): """ Calculate the dimensions and area of a bounding box. @@ -678,17 +680,17 @@ def save_one_box( @threaded def plot_images( - labels: Dict[str, Any], - images: Union[torch.Tensor, np.ndarray] = np.zeros((0, 3, 640, 640), dtype=np.float32), - paths: Optional[List[str]] = None, + labels: dict[str, Any], + images: torch.Tensor | np.ndarray = np.zeros((0, 3, 640, 640), dtype=np.float32), + paths: list[str] | None = None, fname: str = "images.jpg", - names: Optional[Dict[int, str]] = None, - on_plot: Optional[Callable] = None, + names: dict[int, str] | None = None, + on_plot: Callable | None = None, max_size: int = 1920, max_subplots: int = 16, save: bool = True, conf_thres: float = 0.25, -) -> Optional[np.ndarray]: +) -> np.ndarray | None: """ Plot image grid with labels, bounding boxes, masks, and keypoints. @@ -851,7 +853,7 @@ def plot_results( segment: bool = False, pose: bool = False, classify: bool = False, - on_plot: Optional[Callable] = None, + on_plot: Callable | None = None, ): """ Plot training results from a results CSV file. The function supports various types of data including segmentation, diff --git a/ultralytics/utils/tqdm.py b/ultralytics/utils/tqdm.py index 9faea33b..886961b9 100644 --- a/ultralytics/utils/tqdm.py +++ b/ultralytics/utils/tqdm.py @@ -165,11 +165,18 @@ class TQDM: # For bytes with scaling, use binary units if self.unit in ("B", "bytes") and self.unit_scale: - for threshold, unit in [(1073741824, "GB/s"), (1048576, "MB/s"), (1024, "KB/s")]: # 1 << 30, << 20, << 10 - if rate >= threshold: - return f"{rate / threshold:.1f}{unit}" - return f"{rate:.1f}B/s" - + return next( + ( + f"{rate / threshold:.1f}{unit}" + for threshold, unit in [ + (1073741824, "GB/s"), + (1048576, "MB/s"), + (1024, "KB/s"), + ] + if rate >= threshold + ), + f"{rate:.1f}B/s", + ) # For other scalable units, use decimal units if self.unit_scale and self.unit in ("it", "items", ""): for threshold, prefix in [(1000000, "M"), (1000, "K")]: @@ -210,7 +217,7 @@ class TQDM: filled = int(frac * width) bar = "━" * filled + "─" * (width - filled) if filled < width and frac * width - filled > 0.5: - bar = bar[:filled] + "╸" + bar[filled + 1 :] + bar = f"{bar[:filled]}╸{bar[filled + 1 :]}" return bar def _should_update(self, dt: float, dn: int) -> bool: @@ -218,10 +225,7 @@ class TQDM: if self.noninteractive: return False - if self.total and self.n >= self.total: - return True - - return dt >= self.mininterval + return True if self.total and self.n >= self.total else dt >= self.mininterval def _display(self, final: bool = False) -> None: """Display progress bar.""" @@ -449,8 +453,7 @@ if __name__ == "__main__": def process_files(): """Simulate processing files of unknown count.""" - files = [f"file_{i}.txt" for i in range(18)] - return files + return [f"file_{i}.txt" for i in range(18)] pbar = TQDM(desc="Scanning files", unit="files") files = process_files()