From 34b339d0331314808d6564a0213e6b3bc39ff613 Mon Sep 17 00:00:00 2001 From: Glenn Jocher Date: Fri, 10 Jan 2025 17:27:22 +0100 Subject: [PATCH] Apply `ruff==0.9.0` formatting (#18624) Co-authored-by: UltralyticsAssistant --- ultralytics/cfg/__init__.py | 3 +-- ultralytics/data/utils.py | 6 ++---- ultralytics/engine/results.py | 3 +-- ultralytics/models/sam/model.py | 2 +- ultralytics/models/sam/modules/utils.py | 2 +- ultralytics/models/utils/loss.py | 2 +- ultralytics/solutions/streamlit_inference.py | 3 +-- ultralytics/utils/__init__.py | 2 +- ultralytics/utils/callbacks/hub.py | 12 ++++-------- ultralytics/utils/checks.py | 3 +-- ultralytics/utils/downloads.py | 3 +-- ultralytics/utils/loss.py | 6 ++---- 12 files changed, 17 insertions(+), 30 deletions(-) diff --git a/ultralytics/cfg/__init__.py b/ultralytics/cfg/__init__.py index a6551df8d28..cc15b13562f 100644 --- a/ultralytics/cfg/__init__.py +++ b/ultralytics/cfg/__init__.py @@ -473,8 +473,7 @@ def check_dict_alignment(base: Dict, custom: Dict, e=None): """ custom = _handle_deprecation(custom) base_keys, custom_keys = (set(x.keys()) for x in (base, custom)) - mismatched = [k for k in custom_keys if k not in base_keys] - if mismatched: + if mismatched := [k for k in custom_keys if k not in base_keys]: from difflib import get_close_matches string = "" diff --git a/ultralytics/data/utils.py b/ultralytics/data/utils.py index 2ea37091a89..4b9d07af020 100644 --- a/ultralytics/data/utils.py +++ b/ultralytics/data/utils.py @@ -60,8 +60,7 @@ def exif_size(img: Image.Image): s = img.size # (width, height) if img.format == "JPEG": # only support JPEG images try: - exif = img.getexif() - if exif: + if exif := img.getexif(): rotation = exif.get(274, None) # the EXIF key for the orientation tag is 274 if rotation in {6, 8}: # rotation 270 or 90 s = s[1], s[0] @@ -125,8 +124,7 @@ def verify_image_label(args): segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in lb] # (cls, xy1...) lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh) lb = np.array(lb, dtype=np.float32) - nl = len(lb) - if nl: + if nl := len(lb): if keypoint: assert lb.shape[1] == (5 + nkpt * ndim), f"labels require {(5 + nkpt * ndim)} columns each" points = lb[:, 5:].reshape(-1, ndim)[:, :2] diff --git a/ultralytics/engine/results.py b/ultralytics/engine/results.py index 8de0a2e6a1c..eefd29f5f02 100644 --- a/ultralytics/engine/results.py +++ b/ultralytics/engine/results.py @@ -652,12 +652,11 @@ def verbose(self): """ log_string = "" probs = self.probs - boxes = self.boxes if len(self) == 0: return log_string if probs is not None else f"{log_string}(no detections), " if probs is not None: log_string += f"{', '.join(f'{self.names[j]} {probs.data[j]:.2f}' for j in probs.top5)}, " - if boxes: + if boxes := self.boxes: for c in boxes.cls.unique(): n = (boxes.cls == c).sum() # detections per class log_string += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " diff --git a/ultralytics/models/sam/model.py b/ultralytics/models/sam/model.py index 97349a665b7..48816d6bf50 100644 --- a/ultralytics/models/sam/model.py +++ b/ultralytics/models/sam/model.py @@ -106,7 +106,7 @@ def predict(self, source, stream=False, bboxes=None, points=None, labels=None, * ... print(f"Detected {len(r.masks)} masks") """ overrides = dict(conf=0.25, task="segment", mode="predict", imgsz=1024) - kwargs = {**overrides, **kwargs} + kwargs = overrides | kwargs prompts = dict(bboxes=bboxes, points=points, labels=labels) return super().predict(source, stream, prompts=prompts, **kwargs) diff --git a/ultralytics/models/sam/modules/utils.py b/ultralytics/models/sam/modules/utils.py index 8bfb13760d9..36eb9de7447 100644 --- a/ultralytics/models/sam/modules/utils.py +++ b/ultralytics/models/sam/modules/utils.py @@ -54,7 +54,7 @@ def select_closest_cond_frames(frame_idx, cond_frame_outputs, max_cond_frame_num (t for t in cond_frame_outputs if t not in selected_outputs), key=lambda x: abs(x - frame_idx), )[:num_remain] - selected_outputs.update((t, cond_frame_outputs[t]) for t in inds_remain) + selected_outputs |= ((t, cond_frame_outputs[t]) for t in inds_remain) unselected_outputs = {t: v for t, v in cond_frame_outputs.items() if t not in selected_outputs} return selected_outputs, unselected_outputs diff --git a/ultralytics/models/utils/loss.py b/ultralytics/models/utils/loss.py index a42b13413fd..a816ac93350 100644 --- a/ultralytics/models/utils/loss.py +++ b/ultralytics/models/utils/loss.py @@ -244,7 +244,7 @@ def _get_loss( gt_scores[idx] = bbox_iou(pred_bboxes.detach(), gt_bboxes, xywh=True).squeeze(-1) loss = {} - loss.update(self._get_loss_class(pred_scores, targets, gt_scores, len(gt_bboxes), postfix)) + loss |= self._get_loss_class(pred_scores, targets, gt_scores, len(gt_bboxes), postfix) loss.update(self._get_loss_bbox(pred_bboxes, gt_bboxes, postfix)) # if masks is not None and gt_mask is not None: # loss.update(self._get_loss_mask(masks, gt_mask, match_indices, postfix)) diff --git a/ultralytics/solutions/streamlit_inference.py b/ultralytics/solutions/streamlit_inference.py index 31a88baec89..c398acfdcac 100644 --- a/ultralytics/solutions/streamlit_inference.py +++ b/ultralytics/solutions/streamlit_inference.py @@ -62,8 +62,7 @@ def __init__(self, **kwargs: Any): self.selected_ind = [] # List of selected classes for detection or tracking self.model = None # Container for the loaded model instance - self.temp_dict = {"model": None} # Temporary dict to store the model path - self.temp_dict.update(kwargs) + self.temp_dict = {"model": None} | kwargs self.model_path = None # Store model file name with path if self.temp_dict["model"] is not None: self.model_path = self.temp_dict["model"] diff --git a/ultralytics/utils/__init__.py b/ultralytics/utils/__init__.py index f5ff78c1b35..0008f8081e6 100644 --- a/ultralytics/utils/__init__.py +++ b/ultralytics/utils/__init__.py @@ -1243,7 +1243,7 @@ def update(self, *args, **kwargs): """Updates settings, validating keys and types.""" for arg in args: if isinstance(arg, dict): - kwargs.update(arg) + kwargs |= arg for k, v in kwargs.items(): if k not in self.defaults: raise KeyError(f"No Ultralytics setting '{k}'. {self.help_msg}") diff --git a/ultralytics/utils/callbacks/hub.py b/ultralytics/utils/callbacks/hub.py index b1fbea1847f..aa2d1585372 100644 --- a/ultralytics/utils/callbacks/hub.py +++ b/ultralytics/utils/callbacks/hub.py @@ -15,16 +15,14 @@ def on_pretrain_routine_start(trainer): def on_pretrain_routine_end(trainer): """Logs info before starting timer for upload rate limit.""" - session = getattr(trainer, "hub_session", None) - if session: + if session := getattr(trainer, "hub_session", None): # Start timer for upload rate limit session.timers = {"metrics": time(), "ckpt": time()} # start timer on session.rate_limit def on_fit_epoch_end(trainer): """Uploads training progress metrics at the end of each epoch.""" - session = getattr(trainer, "hub_session", None) - if session: + if session := getattr(trainer, "hub_session", None): # Upload metrics after val end all_plots = { **trainer.label_loss_items(trainer.tloss, prefix="train"), @@ -49,8 +47,7 @@ def on_fit_epoch_end(trainer): def on_model_save(trainer): """Saves checkpoints to Ultralytics HUB with rate limiting.""" - session = getattr(trainer, "hub_session", None) - if session: + if session := getattr(trainer, "hub_session", None): # Upload checkpoints with rate limiting is_best = trainer.best_fitness == trainer.fitness if time() - session.timers["ckpt"] > session.rate_limits["ckpt"]: @@ -61,8 +58,7 @@ def on_model_save(trainer): def on_train_end(trainer): """Upload final model and metrics to Ultralytics HUB at the end of training.""" - session = getattr(trainer, "hub_session", None) - if session: + if session := getattr(trainer, "hub_session", None): # Upload final model and metrics with exponential standoff LOGGER.info(f"{PREFIX}Syncing final model...") session.upload_model( diff --git a/ultralytics/utils/checks.py b/ultralytics/utils/checks.py index d9e42cf8bee..335b53aea8c 100644 --- a/ultralytics/utils/checks.py +++ b/ultralytics/utils/checks.py @@ -75,8 +75,7 @@ def parse_requirements(file_path=ROOT.parent / "requirements.txt", package=""): line = line.strip() if line and not line.startswith("#"): line = line.split("#")[0].strip() # ignore inline comments - match = re.match(r"([a-zA-Z0-9-_]+)\s*([<>!=~]+.*)?", line) - if match: + if match := re.match(r"([a-zA-Z0-9-_]+)\s*([<>!=~]+.*)?", line): requirements.append(SimpleNamespace(name=match[1], specifier=match[2].strip() if match[2] else "")) return requirements diff --git a/ultralytics/utils/downloads.py b/ultralytics/utils/downloads.py index 555fbaf5be5..5d535b6f96b 100644 --- a/ultralytics/utils/downloads.py +++ b/ultralytics/utils/downloads.py @@ -269,8 +269,7 @@ def get_google_drive_file_info(link): for k, v in response.cookies.items(): if k.startswith("download_warning"): drive_url += f"&confirm={v}" # v is token - cd = response.headers.get("content-disposition") - if cd: + if cd := response.headers.get("content-disposition"): filename = re.findall('filename="(.+)"', cd)[0] return drive_url, filename diff --git a/ultralytics/utils/loss.py b/ultralytics/utils/loss.py index c6557df4c05..857fccf4f83 100644 --- a/ultralytics/utils/loss.py +++ b/ultralytics/utils/loss.py @@ -189,8 +189,7 @@ def preprocess(self, targets, batch_size, scale_tensor): out = torch.zeros(batch_size, counts.max(), ne - 1, device=self.device) for j in range(batch_size): matches = i == j - n = matches.sum() - if n: + if n := matches.sum(): out[j, :n] = targets[matches, 1:] out[..., 1:5] = xywh2xyxy(out[..., 1:5].mul_(scale_tensor)) return out @@ -630,8 +629,7 @@ def preprocess(self, targets, batch_size, scale_tensor): out = torch.zeros(batch_size, counts.max(), 6, device=self.device) for j in range(batch_size): matches = i == j - n = matches.sum() - if n: + if n := matches.sum(): bboxes = targets[matches, 2:] bboxes[..., :4].mul_(scale_tensor) out[j, :n] = torch.cat([targets[matches, 1:2], bboxes], dim=-1)