YoloDatasetCustomizer 0.2.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (18) hide show
  1. {yolodatasetcustomizer-0.2.0 → yolodatasetcustomizer-0.3.0}/.gitattributes +0 -0
  2. yolodatasetcustomizer-0.3.0/.github/workflows/ci.yml +35 -0
  3. {yolodatasetcustomizer-0.2.0 → yolodatasetcustomizer-0.3.0}/.gitignore +0 -0
  4. {yolodatasetcustomizer-0.2.0 → yolodatasetcustomizer-0.3.0}/.python-version +0 -0
  5. {yolodatasetcustomizer-0.2.0 → yolodatasetcustomizer-0.3.0}/LICENSE +0 -0
  6. {yolodatasetcustomizer-0.2.0 → yolodatasetcustomizer-0.3.0}/PKG-INFO +6 -1
  7. {yolodatasetcustomizer-0.2.0 → yolodatasetcustomizer-0.3.0}/README.md +5 -0
  8. {yolodatasetcustomizer-0.2.0 → yolodatasetcustomizer-0.3.0}/pyproject.toml +15 -1
  9. yolodatasetcustomizer-0.3.0/resources/Improvements.txt +57 -0
  10. {yolodatasetcustomizer-0.2.0 → yolodatasetcustomizer-0.3.0}/src/YoloDatasetCustomizer/__init__.py +1 -1
  11. {yolodatasetcustomizer-0.2.0 → yolodatasetcustomizer-0.3.0}/src/YoloDatasetCustomizer/customizer.py +174 -166
  12. {yolodatasetcustomizer-0.2.0 → yolodatasetcustomizer-0.3.0}/src/YoloDatasetCustomizer/labels.py +71 -71
  13. {yolodatasetcustomizer-0.2.0 → yolodatasetcustomizer-0.3.0}/src/YoloDatasetCustomizer/paths.py +20 -20
  14. {yolodatasetcustomizer-0.2.0 → yolodatasetcustomizer-0.3.0}/src/YoloDatasetCustomizer/reader.py +128 -90
  15. {yolodatasetcustomizer-0.2.0 → yolodatasetcustomizer-0.3.0}/src/YoloDatasetCustomizer/writer.py +41 -41
  16. {yolodatasetcustomizer-0.2.0 → yolodatasetcustomizer-0.3.0}/test/YoloDatasetCustomizer_test.py +124 -7
  17. {yolodatasetcustomizer-0.2.0 → yolodatasetcustomizer-0.3.0}/uv.lock +307 -2
  18. yolodatasetcustomizer-0.2.0/resources/Improvements.txt +0 -33
@@ -0,0 +1,35 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ fail-fast: false
13
+ matrix:
14
+ # "3" resolves to the latest released stable CPython 3.x, so this
15
+ # tracks new releases automatically without needing manual bumps
16
+ python-version: ["3.10", "3"]
17
+ steps:
18
+ - uses: actions/checkout@v4
19
+
20
+ - name: Install uv
21
+ uses: astral-sh/setup-uv@v6
22
+ with:
23
+ python-version: ${{ matrix.python-version }}
24
+
25
+ - name: Install dependencies
26
+ run: uv sync --group dev
27
+
28
+ - name: Lint (ruff)
29
+ run: uv run ruff check src test
30
+
31
+ - name: Type-check (mypy)
32
+ run: uv run mypy
33
+
34
+ - name: Test (pytest)
35
+ run: uv run pytest -q
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: YoloDatasetCustomizer
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Load one or multiple datasets. Reduce, mix or merge into a custom dataset.
5
5
  Project-URL: Homepage, https://github.com/mLuca/YoloDatasetCustomizer
6
6
  Project-URL: Repository, https://github.com/mLuca/YoloDatasetCustomizer
@@ -58,6 +58,11 @@ The project uses uv. Install dependencies and run tests with:
58
58
 
59
59
  uv run pytest
60
60
 
61
+ # Lint & type-check
62
+
63
+ uv run ruff check src test
64
+ uv run mypy
65
+
61
66
  # Build project
62
67
 
63
68
  Build the package
@@ -31,6 +31,11 @@ The project uses uv. Install dependencies and run tests with:
31
31
 
32
32
  uv run pytest
33
33
 
34
+ # Lint & type-check
35
+
36
+ uv run ruff check src test
37
+ uv run mypy
38
+
34
39
  # Build project
35
40
 
36
41
  Build the package
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "YoloDatasetCustomizer"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "Load one or multiple datasets. Reduce, mix or merge into a custom dataset."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -41,4 +41,18 @@ Repository = "https://github.com/mLuca/YoloDatasetCustomizer"
41
41
  dev = [
42
42
  "pytest>=9.1.1",
43
43
  "twine>=6.2.0",
44
+ "ruff>=0.14.0",
45
+ "mypy>=1.18.0",
44
46
  ]
47
+
48
+ [tool.ruff]
49
+ line-length = 120
50
+
51
+ [tool.ruff.lint]
52
+ select = ["E", "F", "W", "I"]
53
+ ignore = ["E501"]
54
+
55
+ [tool.mypy]
56
+ python_version = "3.10"
57
+ files = ["src"]
58
+ ignore_missing_imports = true
@@ -0,0 +1,57 @@
1
+ Priority-ordered improvement list (last reviewed 2026-08-14)
2
+
3
+ FIXED 1. Fix brittle path and OS handling
4
+ Why: The code constructs file paths with string concatenation and assumes Unix-style separators, which can break on Windows and in nested dataset layouts. Since this tool operates on filesystem paths, cross-platform reliability is a core requirement.
5
+
6
+ FIXED 2. Remove mutable default arguments
7
+ Why: class_names: list[str] = [] creates shared state across instances. This is a Python bug pattern that can cause hard-to-trace behavior and incorrect dataset generation when objects are reused.
8
+
9
+ FIXED 3. Fix broken internal state and debug output
10
+ Why: __repr__ references attributes that do not exist, which signals stale or inconsistent internal state. This is a maintainability problem and a sign that code may be harder to trust during debugging.
11
+
12
+ FIXED 4. Refactor the monolithic implementation into smaller modules
13
+ Why: The main file handles reading YAML, writing YAML, copying labels, scanning directories, and building datasets all at once. Splitting responsibilities would reduce complexity, improve testability, and make future features safer to add.
14
+
15
+ FIXED 1. Fix broken copy-failure error handling in customizer.py
16
+ Why: `if not shutil.copyfile(img, destination):` is dead code — copyfile returns a truthy destination path on success and raises on failure, so this branch never triggers and a real copy error (permissions, disk full, locked file) crashes the whole run with an unhandled exception instead of returning False with a clear message.
17
+
18
+ FIXED 2. Fix the path-existence skip logic in create_new_dataset_for_class_names
19
+ Why: `for path in [old_labels_path, old_images_path]: if not os.path.exists(path): ...continue` only continues that 2-item inner loop, not the split-processing loop it's meant to guard. A missing labels/images directory is not actually skipped as intended, so processing silently proceeds against a non-existent path (glob just returns nothing, masking the real problem).
20
+
21
+ FIXED 3. Standardize class-index typing and conversion
22
+ Why: Indices are handled as strings in some places and as numeric concepts in others. This inconsistency increases the chance of subtle label remapping bugs that are especially dangerous in object-detection datasets.
23
+
24
+ 4. Tighten validation and error handling generally
25
+ Why: add_data_sets() prints a warning and continues on bad YAML instead of surfacing a clear, actionable failure or strict mode. Silently skipping broken YAML or missing directories can produce partially valid outputs and make debugging much harder.
26
+
27
+ 5. Stop leaking mutable internal state from getters
28
+ Why: get_found_data_file_paths() and get_class_names() return the live internal set/list rather than a copy. Callers can accidentally mutate the object's internal state from outside, breaking encapsulation.
29
+
30
+ FIXED 6. Add CI (GitHub Actions) for tests, lint, and type-checking
31
+ Why: The package classifies itself as "Production/Stable" and is published to PyPI, but nothing runs tests or checks automatically on push/PR. Bugs like items 1 and 2 above would have been easy to catch with basic CI.
32
+
33
+ FIXED 7. Add lint/type-check tooling (ruff + mypy) to the dev dependency group
34
+ Why: There is currently no configured static analysis. Tooling like this would have flagged the always-true/dead `if not shutil.copyfile(...)` check and similar issues automatically.
35
+
36
+ 8. Replace print()-based warnings/errors with the `logging` module
37
+ Why: A library shouldn't write directly to stdout. Using `logging` lets consumers control verbosity, redirect output, and integrate the tool into larger pipelines.
38
+
39
+ FIXED 9. Clean up naming and spelling inconsistencies
40
+ Why: The misspelling "indeces" is used in some names (copy_by_class_indeces, __generate_new_class_indeces) while the correct "indices" is used elsewhere (get_class_indices, get_indices_for_names) in the same codebase. This is not just cosmetic; it slows down maintenance and increases the chance of mistakes during refactors.
41
+
42
+ 10. Remove or clarify the directory-handling branch in LabelFile.__init__
43
+ Why: `_get_unique_path(file_path) if os.path.isdir(file_path) else ...` produces a non-existent path (by design of _get_unique_path) whenever a directory is passed, which then immediately raises FileNotFoundError. This looks like dead or misleading code with no clear purpose.
44
+
45
+ 11. Make SUPPORTED_IMAGE_FORMATS a class-level constant
46
+ Why: It's currently rebuilt as a public mutable list on every instance in __init__. A class-level tuple/frozenset avoids repeated allocation and accidental external mutation.
47
+
48
+ 12. Add a py.typed marker file
49
+ Why: The package ships inline type hints and is installable from PyPI, but without py.typed, downstream type checkers (mypy/pyright) will ignore those hints for consumers of the published package.
50
+
51
+ 13. Improve test coverage around edge cases
52
+ Why: The current tests cover the happy path well, plus a few negative cases, but not the bugs found above (missing labels/images dir, copy failures) or other realistic failures such as duplicate file names, empty split folders, and unexpected dataset layouts.
53
+
54
+ 14. Clarify and formally validate documented limitations
55
+ Why: The README already explains assumptions like fixed dataset naming and ignored YAML fields (`path`, `script`). Those constraints should be treated as explicit, validated API requirements (and paired with clearer usage examples) so users understand exactly what is supported and what is not.
56
+
57
+ Highest priority overall: items 1 and 2 are real correctness bugs in the core dataset-generation path that can silently produce wrong, incomplete, or crashing output today. Fix those first, then invest in CI and lint tooling (items 6-7) so regressions like this are caught automatically going forward.
@@ -5,7 +5,7 @@ from .labels import LabelFile
5
5
  from .reader import YoloDataFileReader
6
6
  from .writer import YoloDataFileWriter
7
7
 
8
- __version__ = "0.2.0"
8
+ __version__ = "0.3.0"
9
9
  __author__ = "Luca Mazzon"
10
10
  __email__ = "mazzon.luca@gmail.com"
11
11
 
@@ -1,166 +1,174 @@
1
- import glob
2
- import os
3
- import shutil
4
-
5
- import yaml
6
-
7
- from .labels import LabelFile
8
- from .paths import _SPLIT_NAMES, _get_unique_path, _normalize_path
9
- from .reader import YoloDataFileReader
10
- from .writer import YoloDataFileWriter
11
-
12
-
13
- class YoloDatasetCustomizer:
14
- """Find and customize YOLO datasets across one or more directory paths."""
15
-
16
- def __init__(self, data_set_paths: list[str]):
17
- """Initialize with YAML dataset paths or directories to scan for YOLO datasets."""
18
- self.__found_data_file_paths: set[str] = set()
19
- self.__data_sets: list[YoloDataFileReader] = []
20
-
21
- self.add_data_sets(data_set_paths)
22
- self.SUPPORTED_IMAGE_FORMATS = [
23
- ".avif",
24
- ".bmp",
25
- ".dng",
26
- ".heic",
27
- ".jp2",
28
- ".jpeg",
29
- ".jpg",
30
- ".mpo",
31
- ".png",
32
- ".tif",
33
- ".tiff",
34
- ".webp",
35
- ]
36
-
37
- def add_data_sets(self, data_set_paths: list[str]):
38
- """Discover YOLO data.yaml files from explicit paths or directory trees."""
39
- data_set_paths = [_normalize_path(path) for path in data_set_paths]
40
-
41
- self.__found_data_file_paths.update(
42
- [path for path in data_set_paths if os.path.basename(path).lower() == "data.yaml"]
43
- )
44
-
45
- paths_without_file_ending = [
46
- path for path in data_set_paths if os.path.basename(path).lower() != "data.yaml"
47
- ]
48
- for path in paths_without_file_ending:
49
- self.__found_data_file_paths.update(glob.glob(os.path.join(path, "**", "data.yaml"), recursive=True))
50
-
51
- for path in self.__found_data_file_paths:
52
- try:
53
- ydfr = YoloDataFileReader(path)
54
- self.__data_sets.append(ydfr)
55
- except (yaml.YAMLError, TypeError, ValueError) as e:
56
- print(f"ERROR: Issue loading YAML file at {path}: {e}")
57
- except FileNotFoundError:
58
- print(f"ERROR: Yaml file does not exist at {path}")
59
-
60
- def get_found_data_file_paths(self) -> set[str]:
61
- """Return all discovered YOLO dataset YAML file paths."""
62
- return self.__found_data_file_paths
63
-
64
- def get_found_class_names(self) -> set[str]:
65
- """Return the union of all class names from discovered datasets."""
66
- found_classes: set[str] = set()
67
- for ydf in self.__data_sets:
68
- found_classes.update(ydf.get_class_names())
69
- return found_classes
70
-
71
- def create_new_dataset_for_class_names(
72
- self,
73
- class_names: set[str],
74
- dst_path: str = ".",
75
- data_set_name: str = "new_dataset",
76
- ignore_img_formats: bool = False,
77
- ) -> bool:
78
- """Create a filtered dataset containing only the requested classes."""
79
- if len(class_names) == 0:
80
- print("ERROR: No classes selected for new dataset.")
81
- return False
82
-
83
- new_dataset_path = os.path.join(_normalize_path(dst_path), data_set_name)
84
- new_dataset_path = _get_unique_path(new_dataset_path)
85
-
86
- new_class_indeces = self.__generate_new_class_indeces(class_names)
87
- print(f"INFO: New class indeces: {new_class_indeces}")
88
-
89
- for data_set in self.__data_sets:
90
- common_class_names = set(data_set.get_class_names()) & class_names
91
- if not common_class_names:
92
- continue
93
-
94
- old_to_new_index_match: dict[str, str] = {}
95
- for class_name in common_class_names:
96
- old_index = str(data_set.get_class_names().index(class_name))
97
- new_index = new_class_indeces[class_name]
98
- old_to_new_index_match[old_index] = new_index
99
-
100
- for split_name in _SPLIT_NAMES:
101
- for split_path in data_set.get_split_paths_for_split_name(split_name):
102
- old_images_path = os.path.join(_normalize_path(data_set.get_file_dir()), split_path)
103
- old_labels_path = self.__generate_label_path_from_img_path(old_images_path)
104
-
105
- for path in [old_labels_path, old_images_path]:
106
- if not os.path.exists(path):
107
- print(f"WARNING: Path '{path}' does not exist! Skipping it.")
108
- continue
109
-
110
- new_labels_path = os.path.join(new_dataset_path, split_name, "labels")
111
- new_images_path = os.path.join(new_dataset_path, split_name, "images")
112
- os.makedirs(new_labels_path, exist_ok=True)
113
- os.makedirs(new_images_path, exist_ok=True)
114
-
115
- for original_label_file_path in glob.glob(os.path.join(old_labels_path, "*.txt")):
116
- label_file = LabelFile(original_label_file_path)
117
- new_label_file_path = label_file.copy_by_class_indeces(old_to_new_index_match, new_labels_path)
118
- if new_label_file_path:
119
- file_name = os.path.basename(original_label_file_path)
120
- file_name_no_ext = file_name[: file_name.rfind(".")]
121
- corresponding_image_files = glob.glob(os.path.join(old_images_path, f"{file_name_no_ext}.*"))
122
- for img in corresponding_image_files:
123
- try:
124
- _, ext = os.path.splitext(img)
125
- except Exception:
126
- print(f"ERROR: Not a valid image, extension missing for: {img}")
127
- return False
128
-
129
- if not ignore_img_formats and ext.lower() not in self.SUPPORTED_IMAGE_FORMATS:
130
- print(
131
- f"ERROR: Image format not supported by yolo: {img}\n"
132
- f"Supported formats are: {self.SUPPORTED_IMAGE_FORMATS}"
133
- )
134
- return False
135
-
136
- new_image_name, _ = os.path.splitext(os.path.basename(new_label_file_path))
137
- new_image_name = new_image_name + ext
138
- destination = os.path.join(new_images_path, new_image_name)
139
- if not shutil.copyfile(img, destination):
140
- print(
141
- f"ERROR: Image could not be copied:\n"
142
- f"Source: {img}\nDestination: {destination}"
143
- )
144
- return False
145
-
146
- data_file_writer = YoloDataFileWriter(new_dataset_path, list(new_class_indeces.keys()))
147
- try:
148
- data_file_writer.write()
149
- except Exception as e:
150
- print(f"ERROR: Could not write new data.yaml to {new_dataset_path}. Generation of {data_set_name} is incomplete!")
151
- print(f"Exception was: {e}")
152
- return False
153
-
154
- return True
155
-
156
- def __generate_new_class_indeces(self, class_names: set[str]) -> dict[str, str]:
157
- """Generate a fresh label index mapping for the selected class names."""
158
- ret: dict[str, str] = {}
159
- for i, name in enumerate(class_names):
160
- ret[name] = str(i)
161
- return ret
162
-
163
- def __generate_label_path_from_img_path(self, img_path: str) -> str:
164
- """Convert an images directory path into its corresponding labels directory path."""
165
- img_path = _normalize_path(img_path)
166
- return os.path.normpath(os.path.join(os.path.dirname(img_path), "labels"))
1
+ import glob
2
+ import os
3
+ import shutil
4
+
5
+ import yaml
6
+
7
+ from .labels import LabelFile
8
+ from .paths import _SPLIT_NAMES, _get_unique_path, _normalize_path
9
+ from .reader import YoloDataFileReader
10
+ from .writer import YoloDataFileWriter
11
+
12
+
13
+ class YoloDatasetCustomizer:
14
+ """Find and customize YOLO datasets across one or more directory paths."""
15
+
16
+ def __init__(self, data_set_paths: list[str]):
17
+ """Initialize with YAML dataset paths or directories to scan for YOLO datasets."""
18
+ self.__found_data_file_paths: set[str] = set()
19
+ self.__data_sets: list[YoloDataFileReader] = []
20
+
21
+ self.add_data_sets(data_set_paths)
22
+ self.SUPPORTED_IMAGE_FORMATS = [
23
+ ".avif",
24
+ ".bmp",
25
+ ".dng",
26
+ ".heic",
27
+ ".jp2",
28
+ ".jpeg",
29
+ ".jpg",
30
+ ".mpo",
31
+ ".png",
32
+ ".tif",
33
+ ".tiff",
34
+ ".webp",
35
+ ]
36
+
37
+ def add_data_sets(self, data_set_paths: list[str]):
38
+ """Discover YOLO data.yaml files from explicit paths or directory trees."""
39
+ data_set_paths = [_normalize_path(path) for path in data_set_paths]
40
+
41
+ self.__found_data_file_paths.update(
42
+ [path for path in data_set_paths if os.path.basename(path).lower() == "data.yaml"]
43
+ )
44
+
45
+ paths_without_file_ending = [
46
+ path for path in data_set_paths if os.path.basename(path).lower() != "data.yaml"
47
+ ]
48
+ for path in paths_without_file_ending:
49
+ self.__found_data_file_paths.update(glob.glob(os.path.join(path, "**", "data.yaml"), recursive=True))
50
+
51
+ for path in self.__found_data_file_paths:
52
+ try:
53
+ ydfr = YoloDataFileReader(path)
54
+ self.__data_sets.append(ydfr)
55
+ except (yaml.YAMLError, TypeError, ValueError) as e:
56
+ print(f"ERROR: Issue loading YAML file at {path}: {e}")
57
+ except FileNotFoundError:
58
+ print(f"ERROR: Yaml file does not exist at {path}")
59
+
60
+ def get_found_data_file_paths(self) -> set[str]:
61
+ """Return all discovered YOLO dataset YAML file paths."""
62
+ return self.__found_data_file_paths
63
+
64
+ def get_found_class_names(self) -> set[str]:
65
+ """Return the union of all class names from discovered datasets."""
66
+ found_classes: set[str] = set()
67
+ for ydf in self.__data_sets:
68
+ found_classes.update(ydf.get_class_names())
69
+ return found_classes
70
+
71
+ def create_new_dataset_for_class_names(
72
+ self,
73
+ class_names: set[str],
74
+ dst_path: str = ".",
75
+ data_set_name: str = "new_dataset",
76
+ ignore_img_formats: bool = False,
77
+ ) -> bool:
78
+ """Create a filtered dataset containing only the requested classes."""
79
+ if len(class_names) == 0:
80
+ print("ERROR: No classes selected for new dataset.")
81
+ return False
82
+
83
+ new_dataset_path = os.path.join(_normalize_path(dst_path), data_set_name)
84
+ new_dataset_path = _get_unique_path(new_dataset_path)
85
+
86
+ new_class_indices = self.__generate_new_class_indices(class_names)
87
+ print(f"INFO: New class indices: {new_class_indices}")
88
+
89
+ for data_set in self.__data_sets:
90
+ common_class_names = set(data_set.get_class_names()) & class_names
91
+ if not common_class_names:
92
+ continue
93
+
94
+ old_to_new_index_match: dict[str, str] = {}
95
+ for class_name in common_class_names:
96
+ old_indices = data_set.get_indices_for_names({class_name})
97
+ if not old_indices:
98
+ continue
99
+ old_index = next(iter(old_indices))
100
+ new_index = new_class_indices[class_name]
101
+ old_to_new_index_match[old_index] = new_index
102
+
103
+ for split_name in _SPLIT_NAMES:
104
+ for split_path in data_set.get_split_paths_for_split_name(split_name):
105
+ old_images_path = os.path.join(_normalize_path(data_set.get_file_dir()), split_path)
106
+ old_labels_path = self.__generate_label_path_from_img_path(old_images_path)
107
+
108
+ missing_path = next(
109
+ (path for path in (old_labels_path, old_images_path) if not os.path.exists(path)), None
110
+ )
111
+ if missing_path is not None:
112
+ print(f"WARNING: Path '{missing_path}' does not exist! Skipping it.")
113
+ continue
114
+
115
+ new_labels_path = os.path.join(new_dataset_path, split_name, "labels")
116
+ new_images_path = os.path.join(new_dataset_path, split_name, "images")
117
+ os.makedirs(new_labels_path, exist_ok=True)
118
+ os.makedirs(new_images_path, exist_ok=True)
119
+
120
+ for original_label_file_path in glob.glob(os.path.join(old_labels_path, "*.txt")):
121
+ label_file = LabelFile(original_label_file_path)
122
+ new_label_file_path = label_file.copy_by_class_indices(old_to_new_index_match, new_labels_path)
123
+ if new_label_file_path:
124
+ file_name = os.path.basename(original_label_file_path)
125
+ file_name_no_ext = file_name[: file_name.rfind(".")]
126
+ corresponding_image_files = glob.glob(os.path.join(old_images_path, f"{file_name_no_ext}.*"))
127
+ for img in corresponding_image_files:
128
+ try:
129
+ _, ext = os.path.splitext(img)
130
+ except Exception:
131
+ print(f"ERROR: Not a valid image, extension missing for: {img}")
132
+ return False
133
+
134
+ if not ignore_img_formats and ext.lower() not in self.SUPPORTED_IMAGE_FORMATS:
135
+ print(
136
+ f"ERROR: Image format not supported by yolo: {img}\n"
137
+ f"Supported formats are: {self.SUPPORTED_IMAGE_FORMATS}"
138
+ )
139
+ return False
140
+
141
+ new_image_name, _ = os.path.splitext(os.path.basename(new_label_file_path))
142
+ new_image_name = new_image_name + ext
143
+ destination = os.path.join(new_images_path, new_image_name)
144
+ try:
145
+ shutil.copyfile(img, destination)
146
+ except OSError as e:
147
+ print(
148
+ f"ERROR: Image could not be copied:\n"
149
+ f"Source: {img}\nDestination: {destination}\n"
150
+ f"Exception was: {e}"
151
+ )
152
+ return False
153
+
154
+ data_file_writer = YoloDataFileWriter(new_dataset_path, list(new_class_indices.keys()))
155
+ try:
156
+ data_file_writer.write()
157
+ except Exception as e:
158
+ print(f"ERROR: Could not write new data.yaml to {new_dataset_path}. Generation of {data_set_name} is incomplete!")
159
+ print(f"Exception was: {e}")
160
+ return False
161
+
162
+ return True
163
+
164
+ def __generate_new_class_indices(self, class_names: set[str]) -> dict[str, str]:
165
+ """Generate a fresh label index mapping for the selected class names."""
166
+ ret: dict[str, str] = {}
167
+ for i, name in enumerate(class_names):
168
+ ret[name] = str(i)
169
+ return ret
170
+
171
+ def __generate_label_path_from_img_path(self, img_path: str) -> str:
172
+ """Convert an images directory path into its corresponding labels directory path."""
173
+ img_path = _normalize_path(img_path)
174
+ return os.path.normpath(os.path.join(os.path.dirname(img_path), "labels"))