Skip to content

Commit 2efb4af

Browse files
Merge main and resolve conflicts (#2287)
* Reduce rich methods (#2283) remove rich Signed-off-by: Ashwin Vaidya <[email protected]> * Refactor BaseThreshold to Threshold (#2278) * Refactor BaseThreshold to Threshold * Add relative import and add tests Signed-off-by: Samet Akcay <[email protected]> * Revert threshold.py to base.py Signed-off-by: Samet Akcay <[email protected]> * Revert threshold imports Signed-off-by: Samet Akcay <[email protected]> * Update tests/unit/metrics/threshold/test_threshold.py Co-authored-by: Ashwin Vaidya <[email protected]> --------- Signed-off-by: Samet Akcay <[email protected]> Co-authored-by: Ashwin Vaidya <[email protected]> * Enable Ruff Rules: PLW1514 and PLR6201 (#2284) * pre-commit autoupdate Signed-off-by: Samet Akcay <[email protected]> * Enable preview feautures, and disable some of the updated features * Add missing copyrights Signed-off-by: Samet Akcay <[email protected]> * Ignore copyrights in notebooks * "PLW1514", # Add explicit encoding argument Signed-off-by: Samet Akcay <[email protected]> * "PLR6201", # Convert to set Signed-off-by: Samet Akcay <[email protected]> --------- Signed-off-by: Samet Akcay <[email protected]> --------- Signed-off-by: Ashwin Vaidya <[email protected]> Signed-off-by: Samet Akcay <[email protected]> Co-authored-by: Ashwin Vaidya <[email protected]> Co-authored-by: Ashwin Vaidya <[email protected]>
1 parent a298a3a commit 2efb4af

File tree

37 files changed

+147
-135
lines changed

37 files changed

+147
-135
lines changed

pyproject.toml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -166,8 +166,6 @@ lint.ignore = [
166166
"A005", # Module is shadowing a Python built-in
167167
"B909", # Mutation to loop iterable during iteration
168168
"PLR6301", # could be a function, class method or static method
169-
"PLW1514", # Add explicit encoding argument
170-
"PLR6201", # Convert to set
171169
"PLC2701", # Private name import
172170
"PLC0415", # import should be at the top of the file
173171
"PLR0917", # Too many positional arguments

src/anomalib/callbacks/checkpoint.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,10 @@ def _should_skip_saving_checkpoint(self, trainer: Trainer) -> bool:
3535
Overrides the parent method to allow saving during both the ``FITTING`` and ``VALIDATING`` states, and to allow
3636
saving when the global step and last_global_step_saved are both 0 (only for zero-/few-shot models).
3737
"""
38-
is_zero_or_few_shot = trainer.lightning_module.learning_type in [LearningType.ZERO_SHOT, LearningType.FEW_SHOT]
38+
is_zero_or_few_shot = trainer.lightning_module.learning_type in {LearningType.ZERO_SHOT, LearningType.FEW_SHOT}
3939
return (
4040
bool(trainer.fast_dev_run) # disable checkpointing with fast_dev_run
41-
or trainer.state.fn not in [TrainerFn.FITTING, TrainerFn.VALIDATING] # don't save anything during non-fit
41+
or trainer.state.fn not in {TrainerFn.FITTING, TrainerFn.VALIDATING} # don't save anything during non-fit
4242
or trainer.sanity_checking # don't save anything during sanity check
4343
or (self._last_global_step_saved == trainer.global_step and not is_zero_or_few_shot)
4444
)
@@ -52,7 +52,7 @@ def _should_save_on_train_epoch_end(self, trainer: Trainer) -> bool:
5252
if self._save_on_train_epoch_end is not None:
5353
return self._save_on_train_epoch_end
5454

55-
if trainer.lightning_module.learning_type in [LearningType.ZERO_SHOT, LearningType.FEW_SHOT]:
55+
if trainer.lightning_module.learning_type in {LearningType.ZERO_SHOT, LearningType.FEW_SHOT}:
5656
return False
5757

5858
return super()._should_save_on_train_epoch_end(trainer)

src/anomalib/cli/cli.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ def add_arguments_to_parser(self, parser: ArgumentParser) -> None:
149149
parser.add_argument("--metrics.image", type=list[str] | str | None, default=None)
150150
parser.add_argument("--metrics.pixel", type=list[str] | str | None, default=None, required=False)
151151
parser.add_argument("--logging.log_graph", type=bool, help="Log the model to the logger", default=False)
152-
if hasattr(parser, "subcommand") and parser.subcommand not in ("export", "predict"):
152+
if hasattr(parser, "subcommand") and parser.subcommand not in {"export", "predict"}:
153153
parser.link_arguments("task", "data.init_args.task")
154154
parser.add_argument(
155155
"--default_root_dir",
@@ -273,7 +273,7 @@ def _set_install_subcommand(self, action_subcommand: _ActionSubCommands) -> None
273273
def before_instantiate_classes(self) -> None:
274274
"""Modify the configuration to properly instantiate classes and sets up tiler."""
275275
subcommand = self.config["subcommand"]
276-
if subcommand in (*self.subcommands(), "train", "predict"):
276+
if subcommand in {*self.subcommands(), "train", "predict"}:
277277
self.config[subcommand] = update_config(self.config[subcommand])
278278

279279
def instantiate_classes(self) -> None:
@@ -283,7 +283,7 @@ def instantiate_classes(self) -> None:
283283
But for subcommands we do not want to instantiate any trainer specific classes such as datamodule, model, etc
284284
This is because the subcommand is responsible for instantiating and executing code based on the passed config
285285
"""
286-
if self.config["subcommand"] in (*self.subcommands(), "predict"): # trainer commands
286+
if self.config["subcommand"] in {*self.subcommands(), "predict"}: # trainer commands
287287
# since all classes are instantiated, the LightningCLI also creates an unused ``Trainer`` object.
288288
# the minor change here is that engine is instantiated instead of trainer
289289
self.config_init = self.parser.instantiate_classes(self.config)
@@ -296,7 +296,7 @@ def instantiate_classes(self) -> None:
296296
else:
297297
self.config_init = self.parser.instantiate_classes(self.config)
298298
subcommand = self.config["subcommand"]
299-
if subcommand in ("train", "export"):
299+
if subcommand in {"train", "export"}:
300300
self.instantiate_engine()
301301
if "model" in self.config_init[subcommand]:
302302
self.model = self._get(self.config_init, "model")
@@ -352,7 +352,7 @@ def _run_subcommand(self) -> None:
352352

353353
install_kwargs = self.config.get("install", {})
354354
anomalib_install(**install_kwargs)
355-
elif self.config["subcommand"] in (*self.subcommands(), "train", "export", "predict"):
355+
elif self.config["subcommand"] in {*self.subcommands(), "train", "export", "predict"}:
356356
fn = getattr(self.engine, self.subcommand)
357357
fn_kwargs = self._prepare_subcommand_kwargs(self.subcommand)
358358
fn(**fn_kwargs)

src/anomalib/cli/install.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,12 @@ def anomalib_install(option: str = "full", verbose: bool = False) -> int:
5454

5555
# Parse requirements into torch and other requirements.
5656
# This is done to parse the correct version of torch (cpu/cuda).
57-
torch_requirement, other_requirements = parse_requirements(requirements, skip_torch=option not in ("full", "core"))
57+
torch_requirement, other_requirements = parse_requirements(requirements, skip_torch=option not in {"full", "core"})
5858

5959
# Get install args for torch to install it from a specific index-url
6060
install_args: list[str] = []
6161
torch_install_args = []
62-
if option in ("full", "core") and torch_requirement is not None:
62+
if option in {"full", "core"} and torch_requirement is not None:
6363
torch_install_args = get_torch_install_args(torch_requirement)
6464

6565
# Combine torch and other requirements.

src/anomalib/cli/utils/help_formatter.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ def get_verbosity_subcommand() -> dict:
6565
{'subcommand': 'train', 'help': True, 'verbosity': 1}
6666
"""
6767
arguments: dict = {"subcommand": None, "help": False, "verbosity": 2}
68-
if len(sys.argv) >= 2 and sys.argv[1] not in ("--help", "-h"):
68+
if len(sys.argv) >= 2 and sys.argv[1] not in {"--help", "-h"}:
6969
arguments["subcommand"] = sys.argv[1]
7070
if "--help" in sys.argv or "-h" in sys.argv:
7171
arguments["help"] = True
@@ -252,7 +252,7 @@ def format_help(self) -> str:
252252
"""
253253
with self.console.capture() as capture:
254254
section = self._root_section
255-
if self.subcommand in REQUIRED_ARGUMENTS and self.verbosity_level in (0, 1) and len(section.rich_items) > 1:
255+
if self.subcommand in REQUIRED_ARGUMENTS and self.verbosity_level in {0, 1} and len(section.rich_items) > 1:
256256
contents = render_guide(self.subcommand)
257257
for content in contents:
258258
self.console.print(content)

src/anomalib/cli/utils/installation.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def get_cuda_version() -> str | None:
134134
# Check $CUDA_HOME/version.json file.
135135
version_file = Path(cuda_home) / "version.json"
136136
if version_file.is_file():
137-
with Path(version_file).open() as file:
137+
with Path(version_file).open(encoding="utf-8") as file:
138138
data = json.load(file)
139139
cuda_version = data.get("cuda", {}).get("version", None)
140140
if cuda_version is not None:
@@ -319,7 +319,7 @@ def get_torch_install_args(requirement: str | Requirement) -> list[str]:
319319
)
320320
install_args: list[str] = []
321321

322-
if platform.system() in ("Linux", "Windows"):
322+
if platform.system() in {"Linux", "Windows"}:
323323
# Get the hardware suffix (eg., +cpu, +cu116 and +cu118 etc.)
324324
hardware_suffix = get_hardware_suffix(with_available_torch_build=True, torch_version=version)
325325

@@ -339,7 +339,7 @@ def get_torch_install_args(requirement: str | Requirement) -> list[str]:
339339
torch_version,
340340
torchvision_requirement,
341341
]
342-
elif platform.system() in ("macos", "Darwin"):
342+
elif platform.system() in {"macos", "Darwin"}:
343343
torch_version = str(requirement)
344344
install_args += [torch_version]
345345
else:

src/anomalib/cli/utils/openvino.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def add_openvino_export_arguments(parser: ArgumentParser) -> None:
2525
ov_parser = get_common_cli_parser()
2626
# remove redundant keys from mo keys
2727
for arg in ov_parser._actions: # noqa: SLF001
28-
if arg.dest in ("help", "input_model", "output_dir"):
28+
if arg.dest in {"help", "input_model", "output_dir"}:
2929
continue
3030
group.add_argument(f"--ov_args.{arg.dest}", type=arg.type, default=arg.default, help=arg.help)
3131
else:

src/anomalib/data/image/btech.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def make_btech_dataset(path: Path, split: str | Split | None = None) -> DataFram
8181
path = validate_path(path)
8282

8383
samples_list = [
84-
(str(path),) + filename.parts[-3:] for filename in path.glob("**/*") if filename.suffix in (".bmp", ".png")
84+
(str(path),) + filename.parts[-3:] for filename in path.glob("**/*") if filename.suffix in {".bmp", ".png"}
8585
]
8686
if not samples_list:
8787
msg = f"Found 0 images in {path}"

src/anomalib/data/utils/download.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -299,7 +299,7 @@ def extract(file_name: Path, root: Path) -> None:
299299
zip_file.extract(file_info, root)
300300

301301
# Safely extract tar files.
302-
elif file_name.suffix in (".tar", ".gz", ".xz", ".tgz"):
302+
elif file_name.suffix in {".tar", ".gz", ".xz", ".tgz"}:
303303
with tarfile.open(file_name) as tar_file:
304304
members = tar_file.getmembers()
305305
safe_members = [member for member in members if not is_file_potentially_dangerous(member.name)]

src/anomalib/data/utils/tiler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ def __init__(
181181
msg,
182182
)
183183

184-
if self.mode not in (ImageUpscaleMode.PADDING, ImageUpscaleMode.INTERPOLATION):
184+
if self.mode not in {ImageUpscaleMode.PADDING, ImageUpscaleMode.INTERPOLATION}:
185185
msg = f"Unknown tiling mode {self.mode}. Available modes are padding and interpolation"
186186
raise ValueError(msg)
187187

0 commit comments

Comments
 (0)