Coretex
base.py
1 # Copyright (C) 2023 Coretex LLC
2 
3 # This file is part of Coretex.ai
4 
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Affero General Public License for more details.
14 
15 # You should have received a copy of the GNU Affero General Public License
16 # along with this program. If not, see <https://www.gnu.org/licenses/>.
17 
18 from typing import TypeVar, Generic, Optional, List
19 from pathlib import Path
20 
21 import json
22 
23 from ...sample import Sample
24 from ...annotation import ImageDatasetClass, ImageDatasetClasses
25 
26 
27 SampleType = TypeVar("SampleType", bound = "Sample")
28 
29 
30 class BaseImageDataset(Generic[SampleType]):
31 
32  samples: List[SampleType]
33  classes: ImageDatasetClasses
34  path: Path
35 
36  @property
37  def classesPath(self) -> Path:
38  """
39  Returns
40  -------
41  Path -> path to classes.json file
42  """
43 
44  return self.path / "classes.json"
45 
46  def classByName(self, name: str) -> Optional[ImageDatasetClass]:
47  for clazz in self.classes:
48  if clazz.label == name:
49  return clazz
50 
51  return None
52 
53  def _writeClassesToFile(self) -> None:
54  self.path.mkdir(exist_ok = True)
55 
56  with open(self.classesPath, "w") as file:
57  json.dump([clazz.encode() for clazz in self.classes], file)
58 
59  def saveClasses(self, classes: ImageDatasetClasses) -> bool:
60  """
61  Saves provided classes (including their color) to dataset.
62  ImageDataset.classes property will be updated on successful save
63 
64  Parameters
65  ----------
66  classes : List[ImageDatasetClass]
67  list of classes
68 
69  Returns
70  -------
71  bool -> True if dataset classes were saved, False if failed to save dataset classes
72 
73  Example
74  -------
75  >>> from coretex import ImageDatasetClass
76  \b
77  >>> labels = {"car", "bicycle", "person", "tree"}
78  >>> imgDatasetClasses = ImageDatasetClass.generate(labels)
79  >>> imageDatasetObj.saveClasses(imgDatasetClasses)
80  True
81  """
82 
83  self.classes = classes
84  self._writeClassesToFile()
85 
86  return True