code-loader 1.0.94.dev2__py3-none-any.whl → 1.0.99.dev1__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 code-loader might be problematic. Click here for more details.

@@ -38,18 +38,11 @@ class PreprocessResponse:
38
38
  sample_ids: Optional[Union[List[str], List[int]]] = None
39
39
  state: Optional[DataStateType] = None
40
40
  sample_id_type: Optional[Union[Type[str], Type[int]]] = None
41
- sample_ids_to_instance_mappings: Optional[Dict[str, List[str]]] = None # in use only for element instance
42
- instance_to_sample_ids_mappings: Optional[Dict[str, str]] = None # in use only for element instance
43
- instance_id_to_instance_name: Optional[Dict[str, str]] = None # in use only for element instance
44
41
 
45
42
  def __post_init__(self) -> None:
46
43
  def is_valid_string(s: str) -> bool:
47
44
  return bool(re.match(r'^[A-Za-z0-9_]+$', s))
48
45
 
49
- assert self.sample_ids_to_instance_mappings is None, f"Keep sample_ids_to_instance_mappings None when initializing PreprocessResponse"
50
- assert self.instance_to_sample_ids_mappings is None, f"Keep instance_to_sample_ids_mappings None when initializing PreprocessResponse"
51
- assert self.instance_id_to_instance_name is None, f"Keep instance_id_to_instance_name None when initializing PreprocessResponse"
52
-
53
46
  if self.length is not None and self.sample_ids is None:
54
47
  self.sample_ids = [i for i in range(self.length)]
55
48
  self.sample_id_type = int
@@ -72,13 +65,8 @@ class PreprocessResponse:
72
65
  assert self.sample_ids is not None
73
66
  return len(self.sample_ids)
74
67
 
75
- @dataclass
76
- class ElementInstance:
77
- name: str
78
- mask: npt.NDArray[np.float32]
79
68
 
80
69
  SectionCallableInterface = Callable[[Union[int, str], PreprocessResponse], npt.NDArray[np.float32]]
81
- InstanceCallableInterface = Callable[[Union[int, str], PreprocessResponse], List[ElementInstance]]
82
70
 
83
71
  MetadataSectionCallableInterface = Union[
84
72
  Callable[[Union[int, str], PreprocessResponse], int],
@@ -200,10 +188,6 @@ class InputHandler(DatasetBaseHandler):
200
188
  shape: Optional[List[int]] = None
201
189
  channel_dim: Optional[int] = -1
202
190
 
203
- @dataclass
204
- class ElementInstanceMasksHandler:
205
- name: str
206
- function: InstanceCallableInterface
207
191
 
208
192
  @dataclass
209
193
  class GroundTruthHandler(DatasetBaseHandler):
@@ -221,7 +205,7 @@ class MetadataHandler:
221
205
  class PredictionTypeHandler:
222
206
  name: str
223
207
  labels: List[str]
224
- channel_dim: int
208
+ channel_dim: int = -1
225
209
 
226
210
 
227
211
  @dataclass
@@ -239,7 +223,6 @@ class DatasetIntegrationSetup:
239
223
  unlabeled_data_preprocess: Optional[UnlabeledDataPreprocessHandler] = None
240
224
  visualizers: List[VisualizerHandler] = field(default_factory=list)
241
225
  inputs: List[InputHandler] = field(default_factory=list)
242
- instance_masks: List[ElementInstanceMasksHandler] = field(default_factory=list)
243
226
  ground_truths: List[GroundTruthHandler] = field(default_factory=list)
244
227
  metadata: List[MetadataHandler] = field(default_factory=list)
245
228
  prediction_types: List[PredictionTypeHandler] = field(default_factory=list)
@@ -256,5 +239,3 @@ class DatasetSample:
256
239
  metadata_is_none: Dict[str, bool]
257
240
  index: Union[int, str]
258
241
  state: DataStateEnum
259
- instance_masks: Optional[Dict[str, List[ElementInstance]]] = None
260
-
@@ -121,23 +121,19 @@ class LeapGraph:
121
121
  x_label = 'Frequency [Seconds]'
122
122
  y_label = 'Amplitude [Voltage]'
123
123
  x_range = (0.1, 3.0)
124
- legend = ['experiment1', 'experiment2', 'experiment3']
125
- leap_graph = LeapGraph(data=graph_data, x_label=x_label, y_label=y_label, x_range=x_range, legend=legend)
124
+ leap_graph = LeapGraph(data=graph_data, x_label=x_label, y_label=y_label, x_range=x_range)
126
125
  """
127
126
  data: npt.NDArray[np.float32]
128
127
  type: LeapDataType = LeapDataType.Graph
129
128
  x_label: Optional[str] = None
130
129
  y_label: Optional[str] = None
131
130
  x_range: Optional[Tuple[float,float]] = None
132
- legend: Optional[List[str]] = None
133
131
 
134
132
  def __post_init__(self) -> None:
135
133
  validate_type(self.type, LeapDataType.Graph)
136
134
  validate_type(type(self.data), np.ndarray)
137
135
  validate_type(self.data.dtype, np.float32)
138
- validate_type(len(self.data.shape), 2, f'Graph must be of shape 2')
139
- if self.legend:
140
- validate_type(self.data.shape[1], len(self.legend), 'Number of labels supplied should equal the number of graphs')
136
+ validate_type(len(self.data.shape), 2, 'Graph must be of shape 2')
141
137
  validate_type(type(self.x_label), [str, type(None)], 'x_label must be a string or None')
142
138
  validate_type(type(self.y_label), [str, type(None)], 'y_label must be a string or None')
143
139
  validate_type(type(self.x_range), [tuple, type(None)], 'x_range must be a tuple or None')
@@ -10,21 +10,23 @@ from code_loader.contract.datasetclasses import SectionCallableInterface, InputH
10
10
  MetadataSectionCallableInterface, UnlabeledDataPreprocessHandler, CustomLayerHandler, MetricHandler, \
11
11
  CustomCallableInterfaceMultiArgs, ConfusionMatrixCallableInterfaceMultiArgs, LeapData, \
12
12
  CustomMultipleReturnCallableInterfaceMultiArgs, DatasetBaseHandler, custom_latent_space_attribute, \
13
- RawInputsForHeatmap, VisualizerHandlerData, MetricHandlerData, CustomLossHandlerData, SamplePreprocessResponse, \
14
- ElementInstanceMasksHandler, InstanceCallableInterface
13
+ RawInputsForHeatmap, VisualizerHandlerData, MetricHandlerData, CustomLossHandlerData, SamplePreprocessResponse
15
14
  from code_loader.contract.enums import LeapDataType, DataStateEnum, DataStateType, MetricDirection, DatasetMetadataType
16
15
  from code_loader.contract.mapping import NodeConnection, NodeMapping, NodeMappingType
17
16
  from code_loader.contract.responsedataclasses import DatasetTestResultPayload
18
17
  from code_loader.contract.visualizer_classes import map_leap_data_type_to_visualizer_class
19
18
  from code_loader.default_losses import loss_name_to_function
20
19
  from code_loader.default_metrics import metrics_names_to_functions_and_direction
21
- from code_loader.utils import to_numpy_return_wrapper, get_shape, to_numpy_return_masks_wrapper
20
+ from code_loader.utils import to_numpy_return_wrapper, get_shape
22
21
  from code_loader.visualizers.default_visualizers import DefaultVisualizer, \
23
22
  default_graph_visualizer, \
24
23
  default_image_visualizer, default_horizontal_bar_visualizer, default_word_visualizer, \
25
24
  default_image_mask_visualizer, default_text_mask_visualizer, default_raw_data_visualizer, default_video_visualizer
26
25
 
27
26
 
27
+ mapping_runtime_mode_env_var_mame = '__MAPPING_RUNTIME_MODE__'
28
+
29
+
28
30
  class LeapBinder:
29
31
  """
30
32
  Interface to the Tensorleap platform. Provides methods to set up preprocessing,
@@ -235,22 +237,6 @@ class LeapBinder:
235
237
 
236
238
  self._encoder_names.append(name)
237
239
 
238
-
239
- def set_instance_masks(self, function: InstanceCallableInterface, name: str) -> None:
240
- """
241
- Set the instance mask handler function.
242
-
243
- Args:
244
- function (SectionCallableInterface): The input handler function.
245
- name (str): The name of the instance mask section.
246
-
247
- Example:
248
- leap_binder.set_input(input_encoder, name='input_encoder')
249
- """
250
- function = to_numpy_return_masks_wrapper(function)
251
- self.setup_container.instance_masks.append(ElementInstanceMasksHandler(name, function))
252
-
253
-
254
240
  def add_custom_loss(self, function: CustomCallableInterface, name: str) -> None:
255
241
  """
256
242
  Add a custom loss function to the setup.
@@ -1,5 +1,5 @@
1
1
  # mypy: ignore-errors
2
-
2
+ import os
3
3
  from typing import Optional, Union, Callable, List, Dict
4
4
 
5
5
  import numpy as np
@@ -8,22 +8,83 @@ import numpy.typing as npt
8
8
  from code_loader.contract.datasetclasses import CustomCallableInterfaceMultiArgs, \
9
9
  CustomMultipleReturnCallableInterfaceMultiArgs, ConfusionMatrixCallableInterfaceMultiArgs, CustomCallableInterface, \
10
10
  VisualizerCallableInterface, MetadataSectionCallableInterface, PreprocessResponse, SectionCallableInterface, \
11
- ConfusionMatrixElement, SamplePreprocessResponse, InstanceCallableInterface, ElementInstance
11
+ ConfusionMatrixElement, SamplePreprocessResponse, PredictionTypeHandler
12
12
  from code_loader.contract.enums import MetricDirection, LeapDataType, DatasetMetadataType
13
13
  from code_loader import leap_binder
14
14
  from code_loader.contract.mapping import NodeMapping, NodeMappingType, NodeConnection
15
15
  from code_loader.contract.visualizer_classes import LeapImage, LeapImageMask, LeapTextMask, LeapText, LeapGraph, \
16
16
  LeapHorizontalBar, LeapImageWithBBox, LeapImageWithHeatmap
17
+ from code_loader.inner_leap_binder.leapbinder import mapping_runtime_mode_env_var_mame
18
+
19
+
20
+ def _add_mapping_connection(user_unique_name, connection_destinations, arg_names, name, node_mapping_type):
21
+ main_node_mapping = NodeMapping(name, node_mapping_type, user_unique_name, arg_names=arg_names)
22
+ node_inputs = {}
23
+ for arg_name, destination in zip(arg_names, connection_destinations):
24
+ node_inputs[arg_name] = destination.node_mapping
25
+
26
+ leap_binder.mapping_connections.append(NodeConnection(main_node_mapping, node_inputs))
17
27
 
18
28
 
19
29
  def _add_mapping_connections(connects_to, arg_names, node_mapping_type, name):
20
30
  for user_unique_name, connection_destinations in connects_to.items():
21
- main_node_mapping = NodeMapping(name, node_mapping_type, user_unique_name, arg_names=arg_names)
22
- node_inputs = {}
23
- for arg_name, destination in zip(arg_names, connection_destinations):
24
- node_inputs[arg_name] = destination.node_mapping
31
+ _add_mapping_connection(user_unique_name, connection_destinations, arg_names, name, node_mapping_type)
32
+
33
+
34
+
35
+
36
+ def tensorleap_load_model(prediction_types: Optional[List[PredictionTypeHandler]] = None):
37
+ for i, prediction_type in enumerate(prediction_types):
38
+ leap_binder.add_prediction(prediction_type.name, prediction_type.labels, prediction_type.channel_dim, i)
39
+
40
+ def decorating_function(load_model_func):
41
+ class TempMapping:
42
+ pass
43
+
44
+ def mapping_inner():
45
+ class ModelOutputPlaceholder:
46
+ def __init__(self):
47
+ self.node_mapping = NodeMapping('', NodeMappingType.Prediction0)
48
+
49
+ def __getitem__(self, key):
50
+ assert isinstance(key, int), \
51
+ f'Expected key to be an int, got {type(key)} instead.'
52
+
53
+ ret = TempMapping()
54
+ ret.node_mapping = NodeMapping('', NodeMappingType(f'Prediction{str(key)}'))
55
+ return ret
56
+
57
+ class ModelPlaceholder:
58
+ #keras interface
59
+ def __call__(self, arg):
60
+ if isinstance(arg, list):
61
+ for i, elem in enumerate(arg):
62
+ elem.node_mapping.type = NodeMappingType[f'Input{str(i)}']
63
+ else:
64
+ arg.node_mapping.type = NodeMappingType.Input0
65
+
66
+ return ModelOutputPlaceholder()
67
+
68
+ # onnx runtime interface
69
+ def run(self, output_names, input_dict):
70
+ assert output_names is None
71
+ assert isinstance(input_dict, dict), \
72
+ f'Expected input_dict to be a dict, got {type(input_dict)} instead.'
73
+ for i, elem in enumerate(input_dict.values()):
74
+ elem.node_mapping.type = NodeMappingType[f'Input{str(i)}']
75
+
76
+ return ModelOutputPlaceholder()
77
+
78
+ return ModelPlaceholder()
79
+
80
+
81
+ if os.environ[mapping_runtime_mode_env_var_mame]:
82
+ return mapping_inner
83
+ else:
84
+ return load_model_func
85
+
86
+ return decorating_function
25
87
 
26
- leap_binder.mapping_connections.append(NodeConnection(main_node_mapping, node_inputs))
27
88
 
28
89
 
29
90
  def tensorleap_custom_metric(name: str,
@@ -31,8 +92,8 @@ def tensorleap_custom_metric(name: str,
31
92
  compute_insights: Optional[Union[bool, Dict[str, bool]]] = None,
32
93
  connects_to=None):
33
94
  def decorating_function(user_function: Union[CustomCallableInterfaceMultiArgs,
34
- CustomMultipleReturnCallableInterfaceMultiArgs,
35
- ConfusionMatrixCallableInterfaceMultiArgs]):
95
+ CustomMultipleReturnCallableInterfaceMultiArgs,
96
+ ConfusionMatrixCallableInterfaceMultiArgs]):
36
97
  for metric_handler in leap_binder.setup_container.metrics:
37
98
  if metric_handler.metric_handler_data.name == name:
38
99
  raise Exception(f'Metric with name {name} already exists. '
@@ -119,14 +180,31 @@ def tensorleap_custom_metric(name: str,
119
180
  (f'tensorleap_custom_metric validation failed: '
120
181
  f'compute_insights should be boolean. Got {type(compute_insights)}.')
121
182
 
122
-
123
183
  def inner(*args, **kwargs):
124
184
  _validate_input_args(*args, **kwargs)
125
185
  result = user_function(*args, **kwargs)
126
186
  _validate_result(result)
127
187
  return result
128
188
 
129
- return inner
189
+ def mapping_inner(*args, **kwargs):
190
+ user_unique_name = mapping_inner.name
191
+ if 'user_unique_name' in kwargs:
192
+ user_unique_name = kwargs['user_unique_name']
193
+
194
+ ordered_connections = [kwargs[n] for n in mapping_inner.arg_names if n in kwargs]
195
+ ordered_connections = list(args) + ordered_connections
196
+ _add_mapping_connection(user_unique_name, ordered_connections, mapping_inner.arg_names,
197
+ mapping_inner.name, NodeMappingType.Metric)
198
+
199
+ return None
200
+
201
+ mapping_inner.arg_names = leap_binder.setup_container.metrics[-1].metric_handler_data.arg_names
202
+ mapping_inner.name = name
203
+
204
+ if os.environ[mapping_runtime_mode_env_var_mame]:
205
+ return mapping_inner
206
+ else:
207
+ return inner
130
208
 
131
209
  return decorating_function
132
210
 
@@ -186,7 +264,25 @@ def tensorleap_custom_visualizer(name: str, visualizer_type: LeapDataType,
186
264
  _validate_result(result)
187
265
  return result
188
266
 
189
- return inner
267
+ def mapping_inner(*args, **kwargs):
268
+ user_unique_name = mapping_inner.name
269
+ if 'user_unique_name' in kwargs:
270
+ user_unique_name = kwargs['user_unique_name']
271
+
272
+ ordered_connections = [kwargs[n] for n in mapping_inner.arg_names if n in kwargs]
273
+ ordered_connections = list(args) + ordered_connections
274
+ _add_mapping_connection(user_unique_name, ordered_connections, mapping_inner.arg_names,
275
+ mapping_inner.name, NodeMappingType.Visualizer)
276
+
277
+ return None
278
+
279
+ mapping_inner.arg_names = leap_binder.setup_container.visualizers[-1].visualizer_handler_data.arg_names
280
+ mapping_inner.name = name
281
+
282
+ if os.environ[mapping_runtime_mode_env_var_mame]:
283
+ return mapping_inner
284
+ else:
285
+ return inner
190
286
 
191
287
  return decorating_function
192
288
 
@@ -270,66 +366,6 @@ def tensorleap_preprocess():
270
366
 
271
367
  return decorating_function
272
368
 
273
- def tensorleap_element_instance_preprocess(instance_mask_encoder: Callable[[int, PreprocessResponse], List[ElementInstance]]):
274
- def decorating_function(user_function: Callable[[], List[PreprocessResponse]]):
275
- def user_function_instance() -> List[PreprocessResponse]:
276
- result = user_function()
277
- for preprocess_response in result:
278
- sample_ids_to_instance_mappings = {}
279
- instance_to_sample_ids_mappings = {}
280
- instance_id_to_instance_name = {}
281
- all_sample_ids = preprocess_response.sample_ids.copy()
282
- for sample_id in preprocess_response.sample_ids:
283
- instances_masks = instance_mask_encoder(sample_id, preprocess_response)
284
- instance_names = [instance.name for instance in instances_masks]
285
- instances_ids = [f'{sample_id}_{instance_id}' for instance_id in range(len(instances_masks))]
286
- sample_ids_to_instance_mappings[sample_id] = instances_ids
287
- instance_to_sample_ids_mappings[sample_id] = sample_id
288
- instance_id_to_instance_name[sample_id] = None
289
- for instance_id, instance_name in zip(instances_ids, instance_names):
290
- instance_to_sample_ids_mappings[instance_id] = sample_id
291
- instance_id_to_instance_name[instance_id] = instance_name
292
- all_sample_ids.extend(instances_ids)
293
- preprocess_response.sample_ids_to_instance_mappings = sample_ids_to_instance_mappings
294
- preprocess_response.instance_to_sample_ids_mappings = instance_to_sample_ids_mappings
295
- preprocess_response.instance_id_to_instance_name = instance_id_to_instance_name
296
- preprocess_response.sample_ids = all_sample_ids
297
- return result
298
-
299
- def metadata_is_instance(idx: str, preprocess: PreprocessResponse) -> Dict[str, str]:
300
- return {'is_instance': '0',
301
- 'orig_sample_id': preprocess.instance_to_sample_ids_mappings[idx],
302
- 'instance_name': preprocess.instance_id_to_instance_name[idx]}
303
- leap_binder.set_preprocess(user_function_instance)
304
- leap_binder.set_metadata(metadata_is_instance, "metadata_is_instance")
305
-
306
- def _validate_input_args(*args, **kwargs):
307
- assert len(args) == 0 and len(kwargs) == 0, \
308
- (f'tensorleap_element_instance_preprocess validation failed: '
309
- f'The function should not take any arguments. Got {args} and {kwargs}.')
310
-
311
- def _validate_result(result):
312
- assert isinstance(result, list), \
313
- (f'tensorleap_element_instance_preprocess validation failed: '
314
- f'The return type should be a list. Got {type(result)}.')
315
- for i, response in enumerate(result):
316
- assert isinstance(response, PreprocessResponse), \
317
- (f'tensorleap_element_instance_preprocess validation failed: '
318
- f'Element #{i} in the return list should be a PreprocessResponse. Got {type(response)}.')
319
- assert len(set(result)) == len(result), \
320
- (f'tensorleap_element_instance_preprocess validation failed: '
321
- f'The return list should not contain duplicate PreprocessResponse objects.')
322
-
323
- def inner(*args, **kwargs):
324
- _validate_input_args(*args, **kwargs)
325
- result = user_function_instance()
326
- _validate_result(result)
327
- return result
328
-
329
- return inner
330
-
331
- return decorating_function
332
-
333
369
 
334
370
  def tensorleap_unlabeled_preprocess():
335
371
  def decorating_function(user_function: Callable[[], PreprocessResponse]):
@@ -356,38 +392,6 @@ def tensorleap_unlabeled_preprocess():
356
392
  return decorating_function
357
393
 
358
394
 
359
- def tensorleap_instances_masks_encoder(name: str):
360
- def decorating_function(user_function: InstanceCallableInterface):
361
- leap_binder.set_instance_masks(user_function, name)
362
-
363
- def _validate_input_args(sample_id: str, preprocess_response: PreprocessResponse):
364
- assert isinstance(sample_id, str), \
365
- (f'tensorleap_instances_masks_encoder validation failed: '
366
- f'Argument sample_id should be str. Got {type(sample_id)}.')
367
- assert isinstance(preprocess_response, PreprocessResponse), \
368
- (f'tensorleap_instances_masks_encoder validation failed: '
369
- f'Argument preprocess_response should be a PreprocessResponse. Got {type(preprocess_response)}.')
370
- assert type(sample_id) == preprocess_response.sample_id_type, \
371
- (f'tensorleap_instances_masks_encoder validation failed: '
372
- f'Argument sample_id should be as the same type as defined in the preprocess response '
373
- f'{preprocess_response.sample_id_type}. Got {type(sample_id)}.')
374
-
375
- def _validate_result(result):
376
- assert isinstance(result, list), \
377
- (f'tensorleap_instances_masks_encoder validation failed: '
378
- f'Unsupported return type. Should be a numpy array. Got {type(result)}.')
379
-
380
- def inner(sample_id, preprocess_response):
381
- _validate_input_args(sample_id, preprocess_response)
382
- result = user_function(sample_id, preprocess_response)
383
- _validate_result(result)
384
- return result
385
-
386
- return inner
387
-
388
- return decorating_function
389
-
390
-
391
395
  def tensorleap_input_encoder(name: str, channel_dim=-1, model_input_index=None):
392
396
  def decorating_function(user_function: SectionCallableInterface):
393
397
  for input_handler in leap_binder.setup_container.inputs:
@@ -432,7 +436,21 @@ def tensorleap_input_encoder(name: str, channel_dim=-1, model_input_index=None):
432
436
  node_mapping_type = NodeMappingType(f'Input{str(model_input_index)}')
433
437
  inner.node_mapping = NodeMapping(name, node_mapping_type)
434
438
 
435
- return inner
439
+
440
+ def mapping_inner(*args, **kwargs):
441
+ class TempMapping:
442
+ pass
443
+ ret = TempMapping()
444
+ ret.node_mapping = mapping_inner.node_mapping
445
+
446
+ return ret
447
+
448
+ mapping_inner.node_mapping = NodeMapping(name, node_mapping_type)
449
+
450
+ if os.environ[mapping_runtime_mode_env_var_mame]:
451
+ return mapping_inner
452
+ else:
453
+ return inner
436
454
 
437
455
  return decorating_function
438
456
 
@@ -474,9 +492,20 @@ def tensorleap_gt_encoder(name: str):
474
492
 
475
493
  inner.node_mapping = NodeMapping(name, NodeMappingType.GroundTruth)
476
494
 
477
- return inner
495
+ def mapping_inner(*args, **kwargs):
496
+ class TempMapping:
497
+ pass
498
+ ret = TempMapping()
499
+ ret.node_mapping = mapping_inner.node_mapping
500
+
501
+ return ret
478
502
 
503
+ mapping_inner.node_mapping = NodeMapping(name, NodeMappingType.GroundTruth)
479
504
 
505
+ if os.environ[mapping_runtime_mode_env_var_mame]:
506
+ return mapping_inner
507
+ else:
508
+ return inner
480
509
 
481
510
  return decorating_function
482
511
 
@@ -532,7 +561,25 @@ def tensorleap_custom_loss(name: str, connects_to=None):
532
561
  _validate_result(result)
533
562
  return result
534
563
 
535
- return inner
564
+ def mapping_inner(*args, **kwargs):
565
+ user_unique_name = mapping_inner.name
566
+ if 'user_unique_name' in kwargs:
567
+ user_unique_name = kwargs['user_unique_name']
568
+
569
+ ordered_connections = [kwargs[n] for n in mapping_inner.arg_names if n in kwargs]
570
+ ordered_connections = list(args) + ordered_connections
571
+ _add_mapping_connection(user_unique_name, ordered_connections, mapping_inner.arg_names,
572
+ mapping_inner.name, NodeMappingType.CustomLoss)
573
+
574
+ return None
575
+
576
+ mapping_inner.arg_names = leap_binder.setup_container.custom_loss_handlers[-1].custom_loss_handler_data.arg_names
577
+ mapping_inner.name = name
578
+
579
+ if os.environ[mapping_runtime_mode_env_var_mame]:
580
+ return mapping_inner
581
+ else:
582
+ return inner
536
583
 
537
584
  return decorating_function
538
585
 
code_loader/leaploader.py CHANGED
@@ -2,6 +2,7 @@
2
2
  import importlib.util
3
3
  import inspect
4
4
  import io
5
+ import os
5
6
  import sys
6
7
  from contextlib import redirect_stdout
7
8
  from functools import lru_cache
@@ -14,8 +15,7 @@ import numpy.typing as npt
14
15
  from code_loader.contract.datasetclasses import DatasetSample, DatasetBaseHandler, GroundTruthHandler, \
15
16
  PreprocessResponse, VisualizerHandler, LeapData, \
16
17
  PredictionTypeHandler, MetadataHandler, CustomLayerHandler, MetricHandler, VisualizerHandlerData, MetricHandlerData, \
17
- MetricCallableReturnType, CustomLossHandlerData, CustomLossHandler, RawInputsForHeatmap, SamplePreprocessResponse, \
18
- ElementInstance
18
+ MetricCallableReturnType, CustomLossHandlerData, CustomLossHandler, RawInputsForHeatmap, SamplePreprocessResponse
19
19
  from code_loader.contract.enums import DataStateEnum, TestingSectionEnum, DataStateType, DatasetMetadataType
20
20
  from code_loader.contract.exceptions import DatasetScriptException
21
21
  from code_loader.contract.responsedataclasses import DatasetIntegParseResult, DatasetTestResultPayload, \
@@ -23,6 +23,7 @@ from code_loader.contract.responsedataclasses import DatasetIntegParseResult, Da
23
23
  VisualizerInstance, PredictionTypeInstance, ModelSetup, CustomLayerInstance, MetricInstance, CustomLossInstance, \
24
24
  EngineFileContract
25
25
  from code_loader.inner_leap_binder import global_leap_binder
26
+ from code_loader.inner_leap_binder.leapbinder import mapping_runtime_mode_env_var_mame
26
27
  from code_loader.leaploaderbase import LeapLoaderBase
27
28
  from code_loader.utils import get_root_exception_file_and_line_number
28
29
 
@@ -151,22 +152,6 @@ class LeapLoader(LeapLoaderBase):
151
152
  state=state)
152
153
  return sample
153
154
 
154
- def get_sample_with_masks(self, state: DataStateEnum, sample_id: Union[int, str]) -> DatasetSample:
155
- self.exec_script()
156
- preprocess_result = self._preprocess_result()
157
- if state == DataStateEnum.unlabeled and sample_id not in preprocess_result[state].sample_ids:
158
- self._preprocess_result(update_unlabeled_preprocess=True)
159
-
160
- metadata, metadata_is_none = self._get_metadata(state, sample_id)
161
- sample = DatasetSample(inputs=self._get_inputs(state, sample_id),
162
- gt=None if state == DataStateEnum.unlabeled else self._get_gt(state, sample_id),
163
- metadata=metadata,
164
- metadata_is_none=metadata_is_none,
165
- index=sample_id,
166
- state=state,
167
- instance_masks=self._get_instances_masks(state, sample_id))
168
- return sample
169
-
170
155
  def check_dataset(self) -> DatasetIntegParseResult:
171
156
  test_payloads: List[DatasetTestResultPayload] = []
172
157
  setup_response = None
@@ -174,7 +159,23 @@ class LeapLoader(LeapLoaderBase):
174
159
  stdout_steam = io.StringIO()
175
160
  with redirect_stdout(stdout_steam):
176
161
  try:
162
+ # generate mapping
163
+ os.environ[mapping_runtime_mode_env_var_mame] = 'TRUE'
164
+ self.exec_script()
165
+ mapping_connections = global_leap_binder.mapping_connections
166
+ del os.environ[mapping_runtime_mode_env_var_mame]
167
+
168
+ # init global leap binder
169
+ global_leap_binder.__init__()
170
+ self.exec_script.cache_clear()
171
+
172
+ # run parse without mapping
177
173
  self.exec_script()
174
+
175
+ # set mapping connections
176
+ if not global_leap_binder.mapping_connections:
177
+ global_leap_binder.mapping_connections = mapping_connections
178
+
178
179
  preprocess_test_payload = self._check_preprocess()
179
180
  test_payloads.append(preprocess_test_payload)
180
181
  handlers_test_payloads = self._check_handlers()
@@ -190,6 +191,8 @@ class LeapLoader(LeapLoaderBase):
190
191
  general_error = f"Something went wrong. {repr(e.__cause__)} in file {file_name}, line_number: {line_number}\nStacktrace:\n{stacktrace}"
191
192
  is_valid = False
192
193
 
194
+
195
+
193
196
  print_log = stdout_steam.getvalue()
194
197
  is_valid_for_model = bool(global_leap_binder.setup_container.custom_layers)
195
198
  model_setup = self.get_model_setup_response()
@@ -454,16 +457,6 @@ class LeapLoader(LeapLoaderBase):
454
457
  def _get_inputs(self, state: DataStateEnum, sample_id: Union[int, str]) -> Dict[str, npt.NDArray[np.float32]]:
455
458
  return self._get_dataset_handlers(global_leap_binder.setup_container.inputs, state, sample_id)
456
459
 
457
- def _get_instances_masks(self, state: DataStateEnum, sample_id: Union[int, str]) -> Dict[str, List[ElementInstance]]:
458
- preprocess_result = self._preprocess_result()
459
- preprocess_state = preprocess_result[state]
460
- result_agg = {}
461
- for handler in global_leap_binder.setup_container.instance_masks:
462
- handler_result = handler.function(sample_id, preprocess_state)
463
- handler_name = handler.name
464
- result_agg[handler_name] = handler_result
465
- return result_agg
466
-
467
460
  def _get_gt(self, state: DataStateEnum, sample_id: Union[int, str]) -> Dict[str, npt.NDArray[np.float32]]:
468
461
  return self._get_dataset_handlers(global_leap_binder.setup_container.ground_truths, state, sample_id)
469
462
 
@@ -532,18 +525,3 @@ class LeapLoader(LeapLoaderBase):
532
525
  raise Exception("Different id types in preprocess results")
533
526
 
534
527
  return id_type
535
-
536
- def get_instances_data(self, state: DataStateEnum) -> Tuple[Dict[Union[int, str], List[Union[int, str]]], Dict[Union[int, str], Union[int, str]], List[Union[int, str]]]:
537
- """
538
- This Method get the data state and returns two dictionaries that holds the mapping of the sample ids to their
539
- instances and the other way around and the sample ids array.
540
- Args:
541
- state: DataStateEnum state
542
- Returns:
543
- sample_ids_to_instance_mappings: sample id to instance mappings
544
- instance_to_sample_ids_mappings: instance to sample ids mappings
545
- sample_ids: sample ids array
546
- """
547
- preprocess_result = self._preprocess_result()
548
- preprocess_state = preprocess_result[state]
549
- return preprocess_state.sample_ids_to_instance_mappings, preprocess_state.instance_to_sample_ids_mappings, preprocess_state.sample_ids
@@ -2,7 +2,7 @@
2
2
 
3
3
  from abc import abstractmethod
4
4
 
5
- from typing import Dict, List, Union, Type, Optional, Tuple
5
+ from typing import Dict, List, Union, Type, Optional
6
6
 
7
7
  import numpy as np
8
8
  import numpy.typing as npt
@@ -64,14 +64,6 @@ class LeapLoaderBase:
64
64
  def get_sample(self, state: DataStateEnum, sample_id: Union[int, str]) -> DatasetSample:
65
65
  pass
66
66
 
67
- @abstractmethod
68
- def get_sample_with_masks(self, state: DataStateEnum, sample_id: Union[int, str]) -> DatasetSample:
69
- pass
70
-
71
- @abstractmethod
72
- def get_instances_data(self, state: DataStateEnum) -> Tuple[Dict[Union[int, str], List[Union[int, str]]], Dict[Union[int, str], Union[int, str]], List[Union[int, str]]]:
73
- pass
74
-
75
67
  @abstractmethod
76
68
  def check_dataset(self) -> DatasetIntegParseResult:
77
69
  pass
code_loader/utils.py CHANGED
@@ -1,13 +1,12 @@
1
1
  import sys
2
2
  from pathlib import Path
3
3
  from types import TracebackType
4
- from typing import List, Union, Tuple, Any, Callable
4
+ from typing import List, Union, Tuple, Any
5
5
  import traceback
6
6
  import numpy as np
7
7
  import numpy.typing as npt
8
8
 
9
- from code_loader.contract.datasetclasses import SectionCallableInterface, PreprocessResponse, \
10
- InstanceCallableInterface, ElementInstance
9
+ from code_loader.contract.datasetclasses import SectionCallableInterface, PreprocessResponse
11
10
 
12
11
 
13
12
  def to_numpy_return_wrapper(encoder_function: SectionCallableInterface) -> SectionCallableInterface:
@@ -18,15 +17,6 @@ def to_numpy_return_wrapper(encoder_function: SectionCallableInterface) -> Secti
18
17
 
19
18
  return numpy_encoder_function
20
19
 
21
- def to_numpy_return_masks_wrapper(encoder_function: InstanceCallableInterface) -> Callable[
22
- [Union[int, str], PreprocessResponse], List[ElementInstance]]:
23
- def numpy_encoder_function(idx: Union[int, str], samples: PreprocessResponse) -> List[ElementInstance]:
24
- result = encoder_function(idx, samples)
25
- for res in result:
26
- res.mask = np.array(res.mask)
27
- return result
28
- return numpy_encoder_function
29
-
30
20
 
31
21
  def get_root_traceback(exc_tb: TracebackType) -> TracebackType:
32
22
  return_traceback = exc_tb
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: code-loader
3
- Version: 1.0.94.dev2
3
+ Version: 1.0.99.dev1
4
4
  Summary:
5
5
  Home-page: https://github.com/tensorleap/code-loader
6
6
  License: MIT
@@ -1,12 +1,12 @@
1
1
  LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
2
2
  code_loader/__init__.py,sha256=6MMWr0ObOU7hkqQKgOqp4Zp3I28L7joGC9iCbQYtAJg,241
3
3
  code_loader/contract/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
- code_loader/contract/datasetclasses.py,sha256=PT1dMA0FxpzJ75rpc79d_oxn3zJmrdOihKTC46ZEZvI,9139
4
+ code_loader/contract/datasetclasses.py,sha256=sNBHyfdg2uS3rL65kJVZjjNVbSXy0dTQMganldQjGNw,7969
5
5
  code_loader/contract/enums.py,sha256=GEFkvUMXnCNt-GOoz7NJ9ecQZ2PPDettJNOsxsiM0wk,1622
6
6
  code_loader/contract/exceptions.py,sha256=jWqu5i7t-0IG0jGRsKF4DjJdrsdpJjIYpUkN1F4RiyQ,51
7
7
  code_loader/contract/mapping.py,sha256=e11h_sprwOyE32PcqgRq9JvyahQrPzwqgkhmbQLKLQY,1165
8
8
  code_loader/contract/responsedataclasses.py,sha256=6-5DJkYBdXb3UB1eNidTTPPBIYxMjEoMdYDkp9VhH8o,4223
9
- code_loader/contract/visualizer_classes.py,sha256=Wz9eItmoRaKEHa3p0aW0Ypxx4_xUmaZyLBznnTuxwi0,15425
9
+ code_loader/contract/visualizer_classes.py,sha256=_nlukRfW8QeQaQG7G5HfAUSeCuoqslB4xJS2AGI_Nz8,15156
10
10
  code_loader/default_losses.py,sha256=NoOQym1106bDN5dcIk56Elr7ZG5quUHArqfP5-Nyxyo,1139
11
11
  code_loader/default_metrics.py,sha256=v16Mrt2Ze1tXPgfKywGVdRSrkaK4CKLNQztN1UdVqIY,5010
12
12
  code_loader/experiment_api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -20,14 +20,14 @@ code_loader/experiment_api/types.py,sha256=MY8xFARHwdVA7p4dxyhD60ShmttgTvb4qdp1o
20
20
  code_loader/experiment_api/utils.py,sha256=XZHtxge12TS4H4-8PjV3sKuhp8Ud6ojAiIzTZJEqBqc,3304
21
21
  code_loader/experiment_api/workingspace_config_utils.py,sha256=DLzXQCg4dgTV_YgaSbeTVzq-2ja_SQw4zi7LXwKL9cY,990
22
22
  code_loader/inner_leap_binder/__init__.py,sha256=koOlJyMNYzGbEsoIbXathSmQ-L38N_pEXH_HvL7beXU,99
23
- code_loader/inner_leap_binder/leapbinder.py,sha256=wmCOj_YKbRXqLL1k5Tw_FrcZgfmgnVQcjs2ok6wdlww,32362
24
- code_loader/inner_leap_binder/leapbinder_decorators.py,sha256=KNbfm8o7F-3ljys5fbVK8NP6mkPSD_itFceGFTWk4kw,29657
25
- code_loader/leaploader.py,sha256=HPDZb10HPYh18_HjoIYT8ipB5pmVvL5tEI_KFKmHS7g,28866
26
- code_loader/leaploaderbase.py,sha256=tpMVEd97675b_var4hvesjN7EgQzoCbPEayNBut6AvI,4551
27
- code_loader/utils.py,sha256=_j8b60pimoNAvWMRj7hEkkT6C76qES6cZoBFHpXHMxA,2698
23
+ code_loader/inner_leap_binder/leapbinder.py,sha256=FaX0kT-dEQJx4tS3LBfDxjf7Bi1LihkeEfLDHbyEbnM,31778
24
+ code_loader/inner_leap_binder/leapbinder_decorators.py,sha256=xvQw6vVYO8acINLzzkePWetsrWvPBiDp6oge8t3GnC0,30044
25
+ code_loader/leaploader.py,sha256=LN7ngforPp7zGd6_1tONpi4AvOry-wTg7agH0D-gn1c,27233
26
+ code_loader/leaploaderbase.py,sha256=VH0vddRmkqLtcDlYPCO7hfz1_VbKo43lUdHDAbd4iJc,4198
27
+ code_loader/utils.py,sha256=aw2i_fqW_ADjLB66FWZd9DfpCQ7mPdMyauROC5Nd51I,2197
28
28
  code_loader/visualizers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
29
29
  code_loader/visualizers/default_visualizers.py,sha256=669lBpLISLO6my5Qcgn1FLDDeZgHumPf252m4KHY4YM,2555
30
- code_loader-1.0.94.dev2.dist-info/LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
31
- code_loader-1.0.94.dev2.dist-info/METADATA,sha256=5rh-Eu9KRqvossEgh3kk7iSDstW5JYfVnuo6xAhFFCY,854
32
- code_loader-1.0.94.dev2.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
33
- code_loader-1.0.94.dev2.dist-info/RECORD,,
30
+ code_loader-1.0.99.dev1.dist-info/LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
31
+ code_loader-1.0.99.dev1.dist-info/METADATA,sha256=LfhWldl2Byaa2GpWaY2P_V-2xPz8c_tpAMeK6kwrDBI,854
32
+ code_loader-1.0.99.dev1.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
33
+ code_loader-1.0.99.dev1.dist-info/RECORD,,