Skip to content

Commit 57fdd59

Browse files
Bordadependabot[bot]pre-commit-ci[bot]greptile-apps[bot]NabJa
authored
Replace pyupgrade with builtin Ruff's UP rule (#8606)
simplify the lintong and reduce the number of used tools to increase consistency without any formatting loss ### Description A few sentences describing the changes proposed in this pull request. ### Types of changes <!--- Put an `x` in all the boxes that apply, and remove the not applicable items --> - [x] Non-breaking change (fix or new feature that would not break existing functionality). - [ ] Breaking change (fix or new feature that would cause existing functionality to change). - [ ] New tests added to cover the changes. - [ ] Integration tests passed locally by running `./runtests.sh -f -u --net --coverage`. - [ ] Quick tests passed locally by running `./runtests.sh --quick --unittests --disttests`. - [ ] In-line docstrings updated. - [ ] Documentation updated, tested `make html` command in the `docs/` folder. --------- Signed-off-by: dependabot[bot] <[email protected]> Signed-off-by: jirka <[email protected]> Signed-off-by: Jirka Borovec <[email protected]> Signed-off-by: NabJa <[email protected]> Signed-off-by: Yun Liu <[email protected]> Signed-off-by: Lukas Folle <[email protected]> Signed-off-by: reworld223 <[email protected]> Signed-off-by: R. Garcia-Dias <[email protected]> Signed-off-by: ytl0623 <[email protected]> Signed-off-by: Iyassou Shimels <[email protected]> Signed-off-by: Bruce Hashemian <[email protected]> Signed-off-by: Fábio S. Ferreira <[email protected]> Signed-off-by: Fabio Ferreira <[email protected]> Signed-off-by: John Zielke <[email protected]> Signed-off-by: Mason Cleveland <[email protected]> Signed-off-by: Mason C. Cleveland <[email protected]> Signed-off-by: mccle <[email protected]> Signed-off-by: Mohamed Salah <[email protected]> Signed-off-by: Rafael Garcia-Dias <[email protected]> Signed-off-by: sewon.jeon <[email protected]> Signed-off-by: sewon jeon <[email protected]> Signed-off-by: Eric Kerfoot <[email protected]> Signed-off-by: Yue (Knox) Liu <[email protected]> Signed-off-by: alexanderjaus <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> Co-authored-by: NabJa <[email protected]> Co-authored-by: Eric Kerfoot <[email protected]> Co-authored-by: YunLiu <[email protected]> Co-authored-by: Yun Liu <[email protected]> Co-authored-by: Lukas Folle <[email protected]> Co-authored-by: reworld223 <[email protected]> Co-authored-by: Rafael Garcia-Dias <[email protected]> Co-authored-by: ytl0623 <[email protected]> Co-authored-by: Iyassou Shimels <[email protected]> Co-authored-by: Bruce Hashemian <[email protected]> Co-authored-by: Fábio S. Ferreira <[email protected]> Co-authored-by: Fabio Ferreira <[email protected]> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> Co-authored-by: John Zielke <[email protected]> Co-authored-by: Mason C. Cleveland <[email protected]> Co-authored-by: Mohamed Salah <[email protected]> Co-authored-by: sewon jeon <[email protected]> Co-authored-by: Copilot <[email protected]> Co-authored-by: Yue (Knox) Liu <[email protected]> Co-authored-by: Alexander Jaus <[email protected]>
1 parent c44ea23 commit 57fdd59

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

77 files changed

+193
-252
lines changed

.pre-commit-config.yaml

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -30,22 +30,11 @@ repos:
3030
rev: v0.7.0
3131
hooks:
3232
- id: ruff
33-
args:
34-
- --fix
35-
36-
- repo: https://github.com/asottile/pyupgrade
37-
rev: v3.19.0
38-
hooks:
39-
- id: pyupgrade
40-
args: [--py39-plus, --keep-runtime-typing]
41-
name: Upgrade code with exceptions
33+
args: ["--fix"]
4234
exclude: |
4335
(?x)(
4436
^versioneer.py|
45-
^monai/_version.py|
46-
^monai/networks/| # avoid typing rewrites
47-
^monai/apps/detection/utils/anchor_utils.py| # avoid typing rewrites
48-
^tests/test_compute_panoptic_quality.py # avoid typing rewrites
37+
^monai/_version.py
4938
)
5039
5140
- repo: https://github.com/asottile/yesqa

monai/apps/auto3dseg/bundle_gen.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -396,7 +396,7 @@ def _download_algos_url(url: str, at_path: str) -> dict[str, dict[str, str]]:
396396
try:
397397
download_and_extract(url=url, filepath=algo_compressed_file, output_dir=os.path.dirname(at_path))
398398
except Exception as e:
399-
msg = f"Download and extract of {url} failed, attempt {i+1}/{download_attempts}."
399+
msg = f"Download and extract of {url} failed, attempt {i + 1}/{download_attempts}."
400400
if i < download_attempts - 1:
401401
warnings.warn(msg)
402402
time.sleep(i)

monai/apps/deepgrow/dataset.py

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -201,14 +201,9 @@ def _save_data_2d(vol_idx, vol_image, vol_label, dataset_dir, relative_path):
201201
logging.warning(f"Unique labels {unique_labels_count} exceeds 20. Please check if this is correct.")
202202

203203
logging.info(
204-
"{} => Image Shape: {} => {}; Label Shape: {} => {}; Unique Labels: {}".format(
205-
vol_idx,
206-
vol_image.shape,
207-
image_count,
208-
vol_label.shape if vol_label is not None else None,
209-
label_count,
210-
unique_labels_count,
211-
)
204+
f"{vol_idx} => Image Shape: {vol_image.shape} => {image_count};"
205+
f" Label Shape: {vol_label.shape if vol_label is not None else None} => {label_count};"
206+
f" Unique Labels: {unique_labels_count}"
212207
)
213208
return data_list
214209

@@ -259,13 +254,8 @@ def _save_data_3d(vol_idx, vol_image, vol_label, dataset_dir, relative_path):
259254
logging.warning(f"Unique labels {unique_labels_count} exceeds 20. Please check if this is correct.")
260255

261256
logging.info(
262-
"{} => Image Shape: {} => {}; Label Shape: {} => {}; Unique Labels: {}".format(
263-
vol_idx,
264-
vol_image.shape,
265-
image_count,
266-
vol_label.shape if vol_label is not None else None,
267-
label_count,
268-
unique_labels_count,
269-
)
257+
f"{vol_idx} => Image Shape: {vol_image.shape} => {image_count};"
258+
f" Label Shape: {vol_label.shape if vol_label is not None else None} => {label_count};"
259+
f" Unique Labels: {unique_labels_count}"
270260
)
271261
return data_list

monai/apps/detection/networks/retinanet_detector.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -787,7 +787,7 @@ def compute_anchor_matched_idxs(
787787
)
788788

789789
if self.debug:
790-
print(f"Max box overlap between anchors and gt boxes: {torch.max(match_quality_matrix,dim=1)[0]}.")
790+
print(f"Max box overlap between anchors and gt boxes: {torch.max(match_quality_matrix, dim=1)[0]}.")
791791

792792
if torch.max(matched_idxs_per_image) < 0:
793793
warnings.warn(

monai/apps/detection/utils/anchor_utils.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939

4040
from __future__ import annotations
4141

42-
from typing import List, Sequence
42+
from collections.abc import Sequence
4343

4444
import torch
4545
from torch import Tensor, nn
@@ -106,7 +106,7 @@ class AnchorGenerator(nn.Module):
106106
anchor_generator = AnchorGenerator(sizes, aspect_ratios)
107107
"""
108108

109-
__annotations__ = {"cell_anchors": List[torch.Tensor]}
109+
__annotations__ = {"cell_anchors": list[torch.Tensor]}
110110

111111
def __init__(
112112
self,
@@ -174,13 +174,13 @@ def generate_anchors(
174174
if (self.spatial_dims >= 3) and (len(aspect_ratios_t.shape) != 2):
175175
raise ValueError(
176176
f"In {self.spatial_dims}-D image, aspect_ratios for each level should be \
177-
{len(aspect_ratios_t.shape)-1}-D. But got aspect_ratios with shape {aspect_ratios_t.shape}."
177+
{len(aspect_ratios_t.shape) - 1}-D. But got aspect_ratios with shape {aspect_ratios_t.shape}."
178178
)
179179

180180
if (self.spatial_dims >= 3) and (aspect_ratios_t.shape[1] != self.spatial_dims - 1):
181181
raise ValueError(
182182
f"In {self.spatial_dims}-D image, aspect_ratios for each level should has \
183-
shape (_,{self.spatial_dims-1}). But got aspect_ratios with shape {aspect_ratios_t.shape}."
183+
shape (_,{self.spatial_dims - 1}). But got aspect_ratios with shape {aspect_ratios_t.shape}."
184184
)
185185

186186
# if 2d, w:h = 1:aspect_ratios
@@ -364,7 +364,7 @@ class AnchorGeneratorWithAnchorShape(AnchorGenerator):
364364
anchor_generator = AnchorGeneratorWithAnchorShape(feature_map_scales, base_anchor_shapes)
365365
"""
366366

367-
__annotations__ = {"cell_anchors": List[torch.Tensor]}
367+
__annotations__ = {"cell_anchors": list[torch.Tensor]}
368368

369369
def __init__(
370370
self,

monai/apps/detection/utils/detector_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,11 +91,11 @@ def check_training_targets(
9191
if boxes.numel() == 0:
9292
warnings.warn(
9393
f"Warning: Given target boxes has shape of {boxes.shape}. "
94-
f"The detector reshaped it with boxes = torch.reshape(boxes, [0, {2* spatial_dims}])."
94+
f"The detector reshaped it with boxes = torch.reshape(boxes, [0, {2 * spatial_dims}])."
9595
)
9696
else:
9797
raise ValueError(
98-
f"Expected target boxes to be a tensor of shape [N, {2* spatial_dims}], got {boxes.shape}.)."
98+
f"Expected target boxes to be a tensor of shape [N, {2 * spatial_dims}], got {boxes.shape}.)."
9999
)
100100
if not torch.is_floating_point(boxes):
101101
raise ValueError(f"Expected target boxes to be a float tensor, got {boxes.dtype}.")

monai/apps/nnunet/nnunet_bundle.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import os
1414
import shutil
1515
from pathlib import Path
16-
from typing import Any, Optional, Union
16+
from typing import Any
1717

1818
import numpy as np
1919
import torch
@@ -36,17 +36,17 @@
3636

3737

3838
def get_nnunet_trainer(
39-
dataset_name_or_id: Union[str, int],
39+
dataset_name_or_id: str | int,
4040
configuration: str,
41-
fold: Union[int, str],
41+
fold: int | str,
4242
trainer_class_name: str = "nnUNetTrainer",
4343
plans_identifier: str = "nnUNetPlans",
4444
use_compressed_data: bool = False,
4545
continue_training: bool = False,
4646
only_run_validation: bool = False,
4747
disable_checkpointing: bool = False,
4848
device: str = "cuda",
49-
pretrained_model: Optional[str] = None,
49+
pretrained_model: str | None = None,
5050
) -> Any: # type: ignore
5151
"""
5252
Get the nnUNet trainer instance based on the provided configuration.
@@ -166,7 +166,7 @@ class ModelnnUNetWrapper(torch.nn.Module):
166166
restoring network architecture, and setting up the predictor for inference.
167167
"""
168168

169-
def __init__(self, predictor: object, model_folder: Union[str, Path], model_name: str = "model.pt"): # type: ignore
169+
def __init__(self, predictor: object, model_folder: str | Path, model_name: str = "model.pt"): # type: ignore
170170
super().__init__()
171171
self.predictor = predictor
172172

@@ -294,7 +294,7 @@ def forward(self, x: MetaTensor) -> MetaTensor:
294294
return MetaTensor(out_tensor, meta=x.meta)
295295

296296

297-
def get_nnunet_monai_predictor(model_folder: Union[str, Path], model_name: str = "model.pt") -> ModelnnUNetWrapper:
297+
def get_nnunet_monai_predictor(model_folder: str | Path, model_name: str = "model.pt") -> ModelnnUNetWrapper:
298298
"""
299299
Initializes and returns a `nnUNetMONAIModelWrapper` containing the corresponding `nnUNetPredictor`.
300300
The model folder should contain the following files, created during training:
@@ -426,9 +426,9 @@ def get_network_from_nnunet_plans(
426426
plans_file: str,
427427
dataset_file: str,
428428
configuration: str,
429-
model_ckpt: Optional[str] = None,
429+
model_ckpt: str | None = None,
430430
model_key_in_ckpt: str = "model",
431-
) -> Union[torch.nn.Module, Any]:
431+
) -> torch.nn.Module | Any:
432432
"""
433433
Load and initialize a nnUNet network based on nnUNet plans and configuration.
434434
@@ -518,7 +518,7 @@ def convert_monai_bundle_to_nnunet(nnunet_config: dict, bundle_root_folder: str,
518518
from nnunetv2.utilities.dataset_name_id_conversion import maybe_convert_to_dataset_name
519519

520520
def subfiles(
521-
folder: Union[str, Path], prefix: Optional[str] = None, suffix: Optional[str] = None, sort: bool = True
521+
folder: str | Path, prefix: str | None = None, suffix: str | None = None, sort: bool = True
522522
) -> list[str]:
523523
res = [
524524
i.name

monai/auto3dseg/analyzer.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ def __call__(self, data):
285285
d[self.stats_name] = report
286286

287287
torch.set_grad_enabled(restore_grad_state)
288-
logger.debug(f"Get image stats spent {time.time()-start}")
288+
logger.debug(f"Get image stats spent {time.time() - start}")
289289
return d
290290

291291

@@ -366,7 +366,7 @@ def __call__(self, data: Mapping) -> dict:
366366
d[self.stats_name] = report
367367

368368
torch.set_grad_enabled(restore_grad_state)
369-
logger.debug(f"Get foreground image stats spent {time.time()-start}")
369+
logger.debug(f"Get foreground image stats spent {time.time() - start}")
370370
return d
371371

372372

@@ -535,7 +535,7 @@ def __call__(self, data: Mapping[Hashable, MetaTensor]) -> dict[Hashable, MetaTe
535535
d[self.stats_name] = report # type: ignore[assignment]
536536

537537
torch.set_grad_enabled(restore_grad_state)
538-
logger.debug(f"Get label stats spent {time.time()-start}")
538+
logger.debug(f"Get label stats spent {time.time() - start}")
539539
return d # type: ignore[return-value]
540540

541541

@@ -913,9 +913,11 @@ def __init__(
913913
for i, hist_params in enumerate(zip(self.hist_bins, self.hist_range)):
914914
_hist_bins, _hist_range = hist_params
915915
if not isinstance(_hist_bins, int) or _hist_bins < 0:
916-
raise ValueError(f"Expected {i+1}. hist_bins value to be positive integer but got {_hist_bins}")
916+
raise ValueError(f"Expected {i + 1}. hist_bins value to be positive integer but got {_hist_bins}")
917917
if not isinstance(_hist_range, list) or len(_hist_range) != 2:
918-
raise ValueError(f"Expected {i+1}. hist_range values to be list of length 2 but received {_hist_range}")
918+
raise ValueError(
919+
f"Expected {i + 1}. hist_range values to be list of length 2 but received {_hist_range}"
920+
)
919921

920922
def __call__(self, data: dict) -> dict:
921923
"""

monai/data/wsi_reader.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,9 @@ def get_valid_level(
210210
# Set the default value if no resolution parameter is provided.
211211
level = 0
212212
if level >= n_levels:
213-
raise ValueError(f"The maximum level of this image is {n_levels-1} while level={level} is requested)!")
213+
raise ValueError(
214+
f"The maximum level of this image is {n_levels - 1} while level={level} is requested)!"
215+
)
214216

215217
return level
216218

monai/handlers/stats_handler.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,7 @@ def _default_iteration_print(self, engine: Engine) -> None:
260260
"ignoring non-scalar output in StatsHandler,"
261261
" make sure `output_transform(engine.state.output)` returns"
262262
" a scalar or dictionary of key and scalar pairs to avoid this warning."
263-
" {}:{}".format(name, type(value))
263+
f" {name}:{type(value)}"
264264
)
265265
continue # not printing multi dimensional output
266266
out_str += self.key_var_format.format(name, value.item() if isinstance(value, torch.Tensor) else value)
@@ -273,7 +273,7 @@ def _default_iteration_print(self, engine: Engine) -> None:
273273
"ignoring non-scalar output in StatsHandler,"
274274
" make sure `output_transform(engine.state.output)` returns"
275275
" a scalar or a dictionary of key and scalar pairs to avoid this warning."
276-
" {}".format(type(loss))
276+
f" {type(loss)}"
277277
)
278278

279279
if not out_str:

0 commit comments

Comments
 (0)