|
| 1 | +import argparse |
| 2 | +from pathlib import Path |
| 3 | +from typing import Union |
| 4 | + |
| 5 | +from const_utils.arguments import Arguments |
| 6 | +from const_utils.default_values import AppSettings |
| 7 | +from const_utils.parser_help import HelpStrings |
| 8 | +from file_operations.file_operation import FileOperation |
| 9 | +from file_operations.file_remover import FileRemoverMixin |
| 10 | + |
| 11 | + |
| 12 | + |
| 13 | +class CleanAnnotationsOperation(FileOperation, FileRemoverMixin): |
| 14 | + def __init__(self, **kwargs): |
| 15 | + """ |
| 16 | + Cleans orphan annotations from same or different paths with images. |
| 17 | + Unique args: |
| 18 | + a_source: Path - a path to annotations directory. If None - will be set as source_directory value |
| 19 | + a_suffix: Tuple[str, ...] - Pattern for annotations file suffix |
| 20 | + """ |
| 21 | + super().__init__(**kwargs) |
| 22 | + self.a_source = self.settings.a_source |
| 23 | + |
| 24 | + |
| 25 | + @staticmethod |
| 26 | + def add_arguments(settings: AppSettings, parser: argparse.ArgumentParser) -> None: |
| 27 | + parser.add_argument( |
| 28 | + Arguments.a_suffix, |
| 29 | + nargs="+", |
| 30 | + help=HelpStrings.a_suffix, |
| 31 | + default=settings.a_suffix, |
| 32 | + ) |
| 33 | + parser.add_argument( |
| 34 | + Arguments.a_source, |
| 35 | + help=HelpStrings.a_source, |
| 36 | + default=settings.a_source, |
| 37 | + ) |
| 38 | + |
| 39 | + |
| 40 | + def do_task(self) -> None: |
| 41 | + self.logger.info(f"Checking for orphan annotations in {self.settings.a_source}") |
| 42 | + annotation_paths = self.get_files( |
| 43 | + source_directory=self.a_source, |
| 44 | + pattern=self.settings.a_suffix |
| 45 | + ) |
| 46 | + |
| 47 | + image_stems = set(image.stem for image in self.files_for_task) |
| 48 | + |
| 49 | + orphans_removed = 0 |
| 50 | + for a_path in annotation_paths: |
| 51 | + if a_path.stem not in image_stems: |
| 52 | + if self._remove_file(a_path): |
| 53 | + orphans_removed += 1 |
| 54 | + self.logger.info(f"Removed {a_path.stem}") |
| 55 | + |
| 56 | + self.logger.info(f"Removed {orphans_removed} orphan annotations") |
| 57 | + |
| 58 | + @property |
| 59 | + def a_source(self) -> Path: |
| 60 | + return self._a_source |
| 61 | + |
| 62 | + @a_source.setter |
| 63 | + def a_source(self, value: Union[Path, str, None]) -> None: |
| 64 | + """setter for a_source, it might be set to Path type, or rise Type error """ |
| 65 | + if isinstance(value, Path): |
| 66 | + self._a_source = value |
| 67 | + elif isinstance(value, str): |
| 68 | + self._a_source = Path(value) |
| 69 | + elif value is None: |
| 70 | + self._a_source = self.source_directory |
| 71 | + else: |
| 72 | + self.logger.error(f"Invalid value for a_source: {value}") |
| 73 | + raise TypeError(f"Invalid value for a_source, can be Union[Path, str, None], got {type(value)}") |
0 commit comments