konfai 1.1.8__py3-none-any.whl → 1.2.0__py3-none-any.whl

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.

Potentially problematic release.


This version of konfai might be problematic. Click here for more details.

Files changed (36) hide show
  1. konfai/__init__.py +59 -14
  2. konfai/data/augmentation.py +457 -286
  3. konfai/data/data_manager.py +533 -316
  4. konfai/data/patching.py +300 -183
  5. konfai/data/transform.py +408 -275
  6. konfai/evaluator.py +325 -68
  7. konfai/main.py +71 -22
  8. konfai/metric/measure.py +360 -244
  9. konfai/metric/schedulers.py +24 -13
  10. konfai/models/classification/convNeXt.py +187 -81
  11. konfai/models/classification/resnet.py +272 -58
  12. konfai/models/generation/cStyleGan.py +233 -59
  13. konfai/models/generation/ddpm.py +348 -121
  14. konfai/models/generation/diffusionGan.py +757 -358
  15. konfai/models/generation/gan.py +177 -53
  16. konfai/models/generation/vae.py +140 -40
  17. konfai/models/registration/registration.py +135 -52
  18. konfai/models/representation/representation.py +57 -23
  19. konfai/models/segmentation/NestedUNet.py +339 -68
  20. konfai/models/segmentation/UNet.py +140 -30
  21. konfai/network/blocks.py +331 -187
  22. konfai/network/network.py +795 -427
  23. konfai/predictor.py +644 -238
  24. konfai/trainer.py +509 -222
  25. konfai/utils/ITK.py +191 -106
  26. konfai/utils/config.py +152 -95
  27. konfai/utils/dataset.py +326 -455
  28. konfai/utils/utils.py +497 -249
  29. {konfai-1.1.8.dist-info → konfai-1.2.0.dist-info}/METADATA +1 -3
  30. konfai-1.2.0.dist-info/RECORD +38 -0
  31. konfai/utils/registration.py +0 -199
  32. konfai-1.1.8.dist-info/RECORD +0 -39
  33. {konfai-1.1.8.dist-info → konfai-1.2.0.dist-info}/WHEEL +0 -0
  34. {konfai-1.1.8.dist-info → konfai-1.2.0.dist-info}/entry_points.txt +0 -0
  35. {konfai-1.1.8.dist-info → konfai-1.2.0.dist-info}/licenses/LICENSE +0 -0
  36. {konfai-1.1.8.dist-info → konfai-1.2.0.dist-info}/top_level.txt +0 -0
konfai/utils/config.py CHANGED
@@ -1,17 +1,20 @@
1
- import os
2
- import ruamel.yaml
3
- import inspect
4
1
  import collections
2
+ import inspect
3
+ import os
4
+ import types
5
5
  from copy import deepcopy
6
- from typing import Union, Literal, get_origin, get_args, Any
6
+ from typing import Any, Literal, Union, get_args, get_origin
7
+
8
+ import ruamel.yaml
7
9
  import torch
8
- from konfai import CONFIG_FILE
10
+
11
+ from konfai import config_file
9
12
  from konfai.utils.utils import ConfigError
10
13
 
11
14
  yaml = ruamel.yaml.YAML()
12
15
 
13
16
 
14
- class Config():
17
+ class Config:
15
18
 
16
19
  def __init__(self, filename, key) -> None:
17
20
  self.filename = filename
@@ -24,32 +27,30 @@ class Config():
24
27
  os.environ["KONFAI_CONFIG_MODE"] = "interactive" if result == "interactive" else "default"
25
28
  else:
26
29
  exit(0)
27
- with open(self.filename, "w") as f:
28
- pass
29
-
30
- self.yml = open(self.filename, 'r')
30
+
31
+ self.yml = open(self.filename)
31
32
  self.data = yaml.load(self.yml)
32
- if self.data == None:
33
+ if self.data is None:
33
34
  self.data = {}
34
-
35
+
35
36
  self.config = self.data
36
37
 
37
38
  for key in self.keys:
38
- if self.config == None or key not in self.config:
39
- self.config = {key : {}}
40
-
39
+ if self.config is None or key not in self.config:
40
+ self.config = {key: {}}
41
+
41
42
  self.config = self.config[key]
42
43
  return self
43
44
 
44
- def createDictionary(self, data, keys, i) -> dict:
45
+ def create_dictionary(self, data, keys, i) -> dict:
45
46
  if keys[i] not in data:
46
47
  data = {keys[i]: data}
47
48
  if i == 0:
48
49
  return data
49
50
  else:
50
51
  i -= 1
51
- return self.createDictionary(data, keys, i)
52
-
52
+ return self.create_dictionary(data, keys, i)
53
+
53
54
  def merge(self, dict1, dict2) -> dict:
54
55
  result = deepcopy(dict1)
55
56
 
@@ -57,29 +58,34 @@ class Config():
57
58
  if isinstance(value, collections.abc.Mapping):
58
59
  result[key] = self.merge(result.get(key, {}), value)
59
60
  else:
60
- if not dict2[key] == None:
61
+ if dict2[key] is not None:
61
62
  result[key] = deepcopy(dict2[key])
62
63
  return result
63
64
 
64
-
65
- def __exit__(self, type, value, traceback) -> None:
65
+ def __exit__(self, exc_type, value, traceback) -> None:
66
66
  self.yml.close()
67
67
  if os.environ["KONFAI_CONFIG_MODE"] == "remove":
68
- if os.path.exists(CONFIG_FILE()):
69
- os.remove(CONFIG_FILE())
68
+ if os.path.exists(config_file()):
69
+ os.remove(config_file())
70
70
  return
71
- with open(self.filename, 'r') as yml:
71
+ with open(self.filename) as yml:
72
72
  data = yaml.load(yml)
73
- if data == None:
73
+ if data is None:
74
74
  data = {}
75
- with open(self.filename, 'w') as yml:
76
- yaml.dump(self.merge(data, self.createDictionary(self.config, self.keys, len(self.keys)-1)), yml)
77
-
75
+ with open(self.filename, "w") as yml:
76
+ yaml.dump(
77
+ self.merge(
78
+ data,
79
+ self.create_dictionary(self.config, self.keys, len(self.keys) - 1),
80
+ ),
81
+ yml,
82
+ )
83
+
78
84
  @staticmethod
79
- def _getInput(name : str, default : str) -> str:
85
+ def _get_input(name: str, default: str) -> str:
80
86
  try:
81
- return input("{} [{}]: ".format(name, ",".join(default.split(":")[1:]) if len(default.split(":")) else ""))
82
- except:
87
+ return input(f"{name} [{','.join(default.split(':')[1:]) if ':' in default else ''}]: ")
88
+ except Exception:
83
89
  result = input("\nKeep a default configuration file ? (yes,no) : ")
84
90
  if result == "yes":
85
91
  os.environ["KONFAI_CONFIG_MODE"] = "default"
@@ -89,119 +95,143 @@ class Config():
89
95
  return default.split(":")[1] if len(default.split(":")) > 1 else default
90
96
 
91
97
  @staticmethod
92
- def _getInputDefault(name : str, default : Union[str, None], isList : bool = False) -> Union[list[Union[str, None]], str, None]:
93
- if isinstance(default, str) and (default == "default" or (len(default.split(":")) > 1 and default.split(":")[0] == "default")):
98
+ def _get_input_default(name: str, default: str | None, is_list: bool = False) -> list[str | None] | str | None:
99
+ if isinstance(default, str) and (
100
+ default == "default" or (len(default.split(":")) > 1 and default.split(":")[0] == "default")
101
+ ):
94
102
  if os.environ["KONFAI_CONFIG_MODE"] == "interactive":
95
- if isList:
96
- list_tmp = []
103
+ if is_list:
104
+ list_tmp: list[str | None] = []
97
105
  key_tmp = "OK"
98
106
  while (key_tmp != "!" and key_tmp != " ") and os.environ["KONFAI_CONFIG_MODE"] == "interactive":
99
- key_tmp = Config._getInput(name, default)
100
- if (key_tmp != "!" and key_tmp != " "):
107
+ key_tmp = Config._get_input(name, default)
108
+ if key_tmp != "!" and key_tmp != " ":
101
109
  if key_tmp == "":
102
110
  key_tmp = default.split(":")[1] if len(default.split(":")) > 1 else default
103
111
  list_tmp.append(key_tmp)
104
112
  return list_tmp
105
113
  else:
106
- value = Config._getInput(name, default)
114
+ value = Config._get_input(name, default)
107
115
  if value == "":
108
- return default.split(":")[1] if len(default.split(":")) > 1 else default
109
- else:
116
+ return default.split(":")[1] if len(default.split(":")) > 1 else default
117
+ else:
110
118
  return value
111
119
  else:
112
120
  default = default.split(":")[1] if len(default.split(":")) > 1 else default
113
- return [default] if isList else default
121
+ return [default] if is_list else default
114
122
 
115
- def getValue(self, name, default) -> object:
123
+ def get_value(self, name, default) -> object:
116
124
  if name in self.config and self.config[name] is not None:
117
125
  value = self.config[name]
118
- if value == None:
126
+ if value is None:
119
127
  value = default
120
128
  value_config = value
121
129
  else:
122
- value = Config._getInputDefault(name, default if default != inspect._empty else None)
123
-
130
+ value = Config._get_input_default(name, default if default != inspect._empty else None)
131
+
124
132
  value_config = value
125
- if type(value_config) == tuple:
133
+ if isinstance(value_config, tuple):
126
134
  value_config = list(value)
127
-
128
- if type(value_config) == list:
129
- list_tmp = []
135
+
136
+ if isinstance(value_config, list):
137
+ list_tmp = []
130
138
  for key in value_config:
131
- list_tmp.extend(Config._getInputDefault(name, key, isList=True))
132
-
139
+ res = Config._get_input_default(name, key, is_list=True)
140
+ if isinstance(res, list):
141
+ list_tmp.extend(res)
142
+ else:
143
+ list_tmp.append(str(res))
133
144
 
134
145
  value = list_tmp
135
146
  value_config = list_tmp
136
147
 
137
- if type(value) == dict:
148
+ if isinstance(value, dict):
138
149
  key_tmp = []
139
-
150
+
140
151
  value_config = {}
141
152
  dict_value = {}
142
153
  for key in value:
143
- key_tmp.extend(Config._getInputDefault(name, key, isList=True))
154
+ res = Config._get_input_default(name, key, is_list=True)
155
+ if isinstance(res, list):
156
+ key_tmp.extend(res)
157
+ else:
158
+ key_tmp.append(str(res))
144
159
  for key in key_tmp:
145
160
  if key in value:
146
161
  value_tmp = value[key]
147
162
  else:
148
- value_tmp = next(v for k,v in value.items() if "default" in k)
163
+ value_tmp = next(v for k, v in value.items() if "default" in k)
149
164
 
150
165
  value_config[key] = None
151
166
  dict_value[key] = value_tmp
152
167
  value = dict_value
153
168
  if isinstance(self.config, str):
154
- os.environ['KONFAI_CONFIG_VARIABLE'] = "True"
169
+ os.environ["KONFAI_CONFIG_VARIABLE"] = "True"
155
170
  return None
156
171
 
157
172
  self.config[name] = value_config if value_config is not None else "None"
158
173
  if value == "None":
159
174
  value = None
160
175
  return value
161
-
162
- def config(key : Union[str, None] = None):
176
+
177
+
178
+ def config(key: str | None = None):
163
179
  def decorator(function):
164
180
  def new_function(*args, **kwargs):
165
181
  if "config" in kwargs:
166
- filename = kwargs["config"]
167
- if filename == None:
168
- filename = os.environ['KONFAI_CONFIG_FILE']
182
+ filename = kwargs["config"]
183
+ if filename is None:
184
+ filename = os.environ["KONFAI_config_file"]
169
185
  else:
170
- os.environ['KONFAI_CONFIG_FILE'] = filename
171
- key_tmp = kwargs["DL_args"]+("."+key if key is not None else "") if "DL_args" in kwargs else key
172
- without = kwargs["DL_without"] if "DL_without" in kwargs else []
173
- os.environ['KONFAI_CONFIG_PATH'] = key_tmp
186
+ os.environ["KONFAI_config_file"] = filename
187
+ key_tmp = (
188
+ kwargs["konfai_args"] + ("." + key if key is not None else "") if "konfai_args" in kwargs else key
189
+ )
190
+ without = kwargs["konfai_without"] if "konfai_without" in kwargs else []
191
+ if key_tmp is not None:
192
+ os.environ["KONFAI_CONFIG_PATH"] = key_tmp
174
193
  with Config(filename, key_tmp) as config:
175
- os.environ['KONFAI_CONFIG_VARIABLE'] = "False"
176
- kwargs = {}
177
- for param in list(inspect.signature(function).parameters.values())[len(args):]:
194
+ os.environ["KONFAI_CONFIG_VARIABLE"] = "False"
195
+ kwargs = {}
196
+ for param in list(inspect.signature(function).parameters.values())[len(args) :]:
178
197
  if param.name in without:
179
198
  continue
180
-
181
- annotation = param.annotation
182
199
 
200
+ annotation = param.annotation
183
201
  # --- support Literal ---
184
202
  if get_origin(annotation) is Literal:
185
203
  allowed_values = get_args(annotation)
186
204
  default_value = param.default if param.default != inspect._empty else allowed_values[0]
187
- value = config.getValue(param.name, f"default:{default_value}")
205
+ value = config.get_value(param.name, f"default:{default_value}")
188
206
  if value not in allowed_values:
189
207
  raise ConfigError(
190
- f"Invalid value '{value}' for parameter '{param.name} expected one of: {allowed_values}."
208
+ f"Invalid value '{value}' for parameter '{param.name} "
209
+ f"expected one of: {allowed_values}."
191
210
  )
192
211
  kwargs[param.name] = value
193
212
  continue
194
- if str(annotation).startswith("typing.Union") or str(annotation).startswith("typing.Optional"):
213
+
214
+ if (
215
+ str(annotation).startswith("typing.Union")
216
+ or str(annotation).startswith("typing.Optional")
217
+ or get_origin(annotation) is types.UnionType
218
+ ):
195
219
  for i in annotation.__args__:
196
220
  annotation = i
197
221
  break
198
-
222
+
199
223
  if not annotation == inspect._empty:
200
224
  if annotation not in [int, str, bool, float, torch.Tensor]:
201
- if str(annotation).startswith("list") or str(annotation).startswith("tuple") or str(annotation).startswith("typing.Tuple") or str(annotation).startswith("typing.List") or str(annotation).startswith("typing.Sequence"):
225
+ if (
226
+ str(annotation).startswith("list")
227
+ or str(annotation).startswith("tuple")
228
+ or str(annotation).startswith("typing.Tuple")
229
+ or str(annotation).startswith("typing.List")
230
+ or str(annotation).startswith("typing.Sequence")
231
+ ):
202
232
  elem_type = annotation.__args__[0]
203
- values = config.getValue(param.name, param.default)
204
- if getattr(elem_type, '__origin__', None) is Union:
233
+ values = config.get_value(param.name, param.default)
234
+ if getattr(elem_type, "__origin__", None) is Union:
205
235
  valid_types = elem_type.__args__
206
236
  result = []
207
237
  for v in values:
@@ -212,43 +242,70 @@ def config(key : Union[str, None] = None):
212
242
  result.append(t(v) if t != torch.Tensor else v)
213
243
  break
214
244
  except Exception:
215
- continue
245
+ raise ValueError("Merde")
216
246
  kwargs[param.name] = result
217
247
 
218
- elif annotation.__args__[0] in [int, str, bool, float]:
219
- values = config.getValue(param.name, param.default)
248
+ elif annotation.__args__[0] in [
249
+ int,
250
+ str,
251
+ bool,
252
+ float,
253
+ ]:
254
+ values = config.get_value(param.name, param.default)
220
255
  kwargs[param.name] = values
221
256
  else:
222
- raise ConfigError("Config: The config only supports types : config(Object), int, str, bool, float, list[int], list[str], list[bool], list[float], dict[str, Object]")
257
+ raise ConfigError(
258
+ "Config: The config only supports types : config(Object), int, str, bool,"
259
+ " float, list[int], list[str], list[bool], list[float], dict[str, Object]"
260
+ )
223
261
  elif str(annotation).startswith("dict"):
224
- if annotation.__args__[0] == str:
225
- values = config.getValue(param.name, param.default)
226
- if values is not None and annotation.__args__[1] not in [int, str, bool, float, Any]:
262
+ if annotation.__args__[0] is str:
263
+ values = config.get_value(param.name, param.default)
264
+ if values is not None and annotation.__args__[1] not in [
265
+ int,
266
+ str,
267
+ bool,
268
+ float,
269
+ Any,
270
+ ]:
227
271
  try:
228
- kwargs[param.name] = {value : annotation.__args__[1](config = filename, DL_args = key_tmp+"."+param.name+"."+value) for value in values}
272
+ kwargs[param.name] = {
273
+ value: annotation.__args__[1](
274
+ config=filename,
275
+ konfai_args=str(key_tmp) + "." + param.name + "." + value,
276
+ )
277
+ for value in values
278
+ }
229
279
  except ValueError as e:
230
280
  raise ValueError(e)
231
281
  except Exception as e:
232
- raise ConfigError("{} {}".format(values, e))
282
+ raise ConfigError(f"{values} {e}")
233
283
  else:
234
284
 
235
285
  kwargs[param.name] = values
236
- else:
237
- raise ConfigError("Config: The config only supports types : config(Object), int, str, bool, float, list[int], list[str], list[bool], list[float], dict[str, Object]")
286
+ else:
287
+ raise ConfigError(
288
+ "Config: The config only supports types : config(Object), int, str, bool,"
289
+ " float, list[int], list[str], list[bool], list[float], dict[str, Object]"
290
+ )
238
291
  else:
239
292
  try:
240
- kwargs[param.name] = annotation(config = filename, DL_args = key_tmp)
293
+ kwargs[param.name] = annotation(config=filename, konfai_args=key_tmp)
241
294
  except Exception as e:
242
- raise ConfigError("Failed to instantiate {} with type {}, error {} ".format(param.name, annotation, e))
243
-
244
- if os.environ['KONFAI_CONFIG_VARIABLE'] == "True":
245
- os.environ['KONFAI_CONFIG_VARIABLE'] = "False"
295
+ raise ConfigError(
296
+ f"Failed to instantiate {param.name} with type {annotation}, error {e} "
297
+ )
298
+
299
+ if os.environ["KONFAI_CONFIG_VARIABLE"] == "True":
300
+ os.environ["KONFAI_CONFIG_VARIABLE"] = "False"
246
301
  kwargs[param.name] = None
247
302
  else:
248
- kwargs[param.name] = config.getValue(param.name, param.default)
303
+ kwargs[param.name] = config.get_value(param.name, param.default)
249
304
  elif param.name != "self":
250
- kwargs[param.name] = config.getValue(param.name, param.default)
305
+ kwargs[param.name] = config.get_value(param.name, param.default)
251
306
  result = function(*args, **kwargs)
252
307
  return result
308
+
253
309
  return new_function
310
+
254
311
  return decorator