code-loader 1.0.119rc2__py3-none-any.whl → 1.0.121__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.

@@ -40,12 +40,10 @@ class PreprocessResponse:
40
40
  sample_id_type: Optional[Union[Type[str], Type[int]]] = None
41
41
  sample_ids_to_instance_mappings: Optional[Dict[str, List[str]]] = None # in use only for element instance
42
42
  instance_to_sample_ids_mappings: Optional[Dict[str, str]] = None # in use only for element instance
43
- instance_ids_to_names: Optional[Dict[str, str]] = None # in use only for element instance
44
43
 
45
44
  def __post_init__(self) -> None:
46
45
  assert self.sample_ids_to_instance_mappings is None, f"Keep sample_ids_to_instance_mappings None when initializing PreprocessResponse"
47
46
  assert self.instance_to_sample_ids_mappings is None, f"Keep instance_to_sample_ids_mappings None when initializing PreprocessResponse"
48
- assert self.instance_ids_to_names is None, f"Keep instance_ids_to_names None when initializing PreprocessResponse"
49
47
 
50
48
  if self.length is not None and self.sample_ids is None:
51
49
  self.sample_ids = [i for i in range(self.length)]
@@ -73,7 +71,9 @@ class ElementInstance:
73
71
  mask: npt.NDArray[np.float32]
74
72
 
75
73
  SectionCallableInterface = Callable[[Union[int, str], PreprocessResponse], npt.NDArray[np.float32]]
76
- InstanceCallableInterface = Callable[[Union[int, str], PreprocessResponse], List[ElementInstance]]
74
+ InstanceCallableInterface = Callable[[Union[int, str], PreprocessResponse, int], Optional[ElementInstance]]
75
+ InstanceLengthCallableInterface = Callable[[Union[int, str], PreprocessResponse], int]
76
+
77
77
 
78
78
  MetadataSectionCallableInterface = Union[
79
79
  Callable[[Union[int, str], PreprocessResponse], int],
@@ -212,6 +212,11 @@ class MetadataHandler:
212
212
  metadata_type: Optional[Union[DatasetMetadataType, Dict[str, DatasetMetadataType]]] = None
213
213
 
214
214
 
215
+ @dataclass
216
+ class CustomLatentSpaceHandler:
217
+ function: SectionCallableInterface
218
+ name: str = 'custom_latent_space'
219
+
215
220
  @dataclass
216
221
  class PredictionTypeHandler:
217
222
  name: str
@@ -241,6 +246,7 @@ class DatasetIntegrationSetup:
241
246
  custom_loss_handlers: List[CustomLossHandler] = field(default_factory=list)
242
247
  metrics: List[MetricHandler] = field(default_factory=list)
243
248
  custom_layers: Dict[str, CustomLayerHandler] = field(default_factory=dict)
249
+ custom_latent_space: Optional[CustomLatentSpaceHandler] = None
244
250
 
245
251
 
246
252
  @dataclass
@@ -251,5 +257,6 @@ class DatasetSample:
251
257
  metadata_is_none: Dict[str, bool]
252
258
  index: Union[int, str]
253
259
  state: DataStateEnum
254
- instance_masks: Optional[Dict[str, List[ElementInstance]]] = None
260
+ custom_latent_space: Optional[npt.NDArray[np.float32]] = None
261
+ instance_masks: Optional[Dict[str, ElementInstance]] = None
255
262
 
@@ -11,7 +11,7 @@ from code_loader.contract.datasetclasses import SectionCallableInterface, InputH
11
11
  CustomCallableInterfaceMultiArgs, ConfusionMatrixCallableInterfaceMultiArgs, LeapData, \
12
12
  CustomMultipleReturnCallableInterfaceMultiArgs, DatasetBaseHandler, custom_latent_space_attribute, \
13
13
  RawInputsForHeatmap, VisualizerHandlerData, MetricHandlerData, CustomLossHandlerData, SamplePreprocessResponse, \
14
- ElementInstanceMasksHandler, InstanceCallableInterface
14
+ ElementInstanceMasksHandler, InstanceCallableInterface, CustomLatentSpaceHandler
15
15
  from code_loader.contract.enums import LeapDataType, DataStateEnum, DataStateType, MetricDirection, DatasetMetadataType
16
16
  from code_loader.contract.mapping import NodeConnection, NodeMapping, NodeMappingType
17
17
  from code_loader.contract.responsedataclasses import DatasetTestResultPayload
@@ -421,6 +421,19 @@ class LeapBinder:
421
421
  """
422
422
  self.setup_container.metadata.append(MetadataHandler(name, function, metadata_type))
423
423
 
424
+ def set_custom_latent_space(self, function: SectionCallableInterface) -> None:
425
+ """
426
+ Set a custom latent space function.
427
+
428
+ Args:
429
+ function (SectionCallableInterface): The metadata handler function.
430
+ This function receives:
431
+ subset (PreprocessResponse): The subset of the data.
432
+ index (int): The index of the sample within the subset.
433
+ This function should numpy float32 array contains the latent space vec of the sample.
434
+ """
435
+ self.setup_container.custom_latent_space = CustomLatentSpaceHandler(function)
436
+
424
437
  def set_custom_layer(self, custom_layer: Type[Any], name: str, inspect_layer: bool = False,
425
438
  kernel_index: Optional[int] = None, use_custom_latent_space: bool = False) -> None:
426
439
  """
@@ -8,7 +8,8 @@ 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, PredictionTypeHandler, InstanceCallableInterface, ElementInstance
11
+ ConfusionMatrixElement, SamplePreprocessResponse, PredictionTypeHandler, InstanceCallableInterface, ElementInstance, \
12
+ InstanceLengthCallableInterface
12
13
  from code_loader.contract.enums import MetricDirection, LeapDataType, DatasetMetadataType
13
14
  from code_loader import leap_binder
14
15
  from code_loader.contract.mapping import NodeMapping, NodeMappingType, NodeConnection
@@ -443,6 +444,55 @@ def tensorleap_metadata(
443
444
  return decorating_function
444
445
 
445
446
 
447
+
448
+ def tensorleap_custom_latent_space():
449
+ def decorating_function(user_function: SectionCallableInterface):
450
+ def _validate_input_args(sample_id: Union[int, str], preprocess_response: PreprocessResponse):
451
+ assert isinstance(sample_id, (int, str)), \
452
+ (f'tensorleap_custom_latent_space validation failed: '
453
+ f'Argument sample_id should be either int or str. Got {type(sample_id)}.')
454
+ assert isinstance(preprocess_response, PreprocessResponse), \
455
+ (f'tensorleap_custom_latent_space validation failed: '
456
+ f'Argument preprocess_response should be a PreprocessResponse. Got {type(preprocess_response)}.')
457
+ assert type(sample_id) == preprocess_response.sample_id_type, \
458
+ (f'tensorleap_custom_latent_space validation failed: '
459
+ f'Argument sample_id should be as the same type as defined in the preprocess response '
460
+ f'{preprocess_response.sample_id_type}. Got {type(sample_id)}.')
461
+
462
+ def _validate_result(result):
463
+ assert isinstance(result, np.ndarray), \
464
+ (f'tensorleap_custom_loss validation failed: '
465
+ f'The return type should be a numpy array. Got {type(result)}.')
466
+
467
+ def inner_without_validate(sample_id, preprocess_response):
468
+ global _called_from_inside_tl_decorator
469
+ _called_from_inside_tl_decorator += 1
470
+
471
+ try:
472
+ result = user_function(sample_id, preprocess_response)
473
+ finally:
474
+ _called_from_inside_tl_decorator -= 1
475
+
476
+ return result
477
+
478
+ leap_binder.set_custom_latent_space(inner_without_validate)
479
+
480
+ def inner(sample_id, preprocess_response):
481
+ if os.environ.get(mapping_runtime_mode_env_var_mame):
482
+ return None
483
+
484
+ _validate_input_args(sample_id, preprocess_response)
485
+
486
+ result = inner_without_validate(sample_id, preprocess_response)
487
+
488
+ _validate_result(result)
489
+ return result
490
+
491
+ return inner
492
+
493
+ return decorating_function
494
+
495
+
446
496
  def tensorleap_preprocess():
447
497
  def decorating_function(user_function: Callable[[], List[PreprocessResponse]]):
448
498
  leap_binder.set_preprocess(user_function)
@@ -480,29 +530,24 @@ def tensorleap_preprocess():
480
530
 
481
531
 
482
532
  def tensorleap_element_instance_preprocess(
483
- instance_mask_encoder: Callable[[str, PreprocessResponse], List[ElementInstance]]):
533
+ instance_length_encoder: InstanceLengthCallableInterface):
484
534
  def decorating_function(user_function: Callable[[], List[PreprocessResponse]]):
485
535
  def user_function_instance() -> List[PreprocessResponse]:
486
536
  result = user_function()
487
537
  for preprocess_response in result:
488
538
  sample_ids_to_instance_mappings = {}
489
539
  instance_to_sample_ids_mappings = {}
490
- instance_ids_to_names = {}
491
540
  all_sample_ids = preprocess_response.sample_ids.copy()
492
541
  for sample_id in preprocess_response.sample_ids:
493
- instances_masks = instance_mask_encoder(sample_id, preprocess_response)
494
- instances_ids = [f'{sample_id}_{instance_id}' for instance_id in range(len(instances_masks))]
542
+ instances_length = instance_length_encoder(sample_id, preprocess_response)
543
+ instances_ids = [f'{sample_id}_{instance_id}' for instance_id in range(instances_length)]
495
544
  sample_ids_to_instance_mappings[sample_id] = instances_ids
496
545
  instance_to_sample_ids_mappings[sample_id] = sample_id
497
- instance_names = [instance.name for instance in instances_masks]
498
- instance_ids_to_names[sample_id] = 'none'
499
- for instance_id, instance_name in zip(instances_ids, instance_names):
546
+ for instance_id in instances_ids:
500
547
  instance_to_sample_ids_mappings[instance_id] = sample_id
501
- instance_ids_to_names[instance_id] = instance_name
502
548
  all_sample_ids.extend(instances_ids)
503
549
  preprocess_response.sample_ids_to_instance_mappings = sample_ids_to_instance_mappings
504
550
  preprocess_response.instance_to_sample_ids_mappings = instance_to_sample_ids_mappings
505
- preprocess_response.instance_ids_to_names = instance_ids_to_names
506
551
  preprocess_response.sample_ids = all_sample_ids
507
552
  return result
508
553
 
@@ -571,7 +616,7 @@ def tensorleap_unlabeled_preprocess():
571
616
 
572
617
  def tensorleap_instances_masks_encoder(name: str):
573
618
  def decorating_function(user_function: InstanceCallableInterface):
574
- def _validate_input_args(sample_id: str, preprocess_response: PreprocessResponse):
619
+ def _validate_input_args(sample_id: str, preprocess_response: PreprocessResponse, instance_id: int):
575
620
  assert isinstance(sample_id, str), \
576
621
  (f'tensorleap_instances_masks_encoder validation failed: '
577
622
  f'Argument sample_id should be str. Got {type(sample_id)}.')
@@ -582,11 +627,61 @@ def tensorleap_instances_masks_encoder(name: str):
582
627
  (f'tensorleap_instances_masks_encoder validation failed: '
583
628
  f'Argument sample_id should be as the same type as defined in the preprocess response '
584
629
  f'{preprocess_response.sample_id_type}. Got {type(sample_id)}.')
630
+ assert isinstance(instance_id, int), \
631
+ (f'tensorleap_instances_masks_encoder validation failed: '
632
+ f'Argument instance_id should be int. Got {type(instance_id)}.')
585
633
 
586
634
  def _validate_result(result):
587
- assert isinstance(result, list), \
635
+ assert isinstance(result, ElementInstance) or (result is None), \
588
636
  (f'tensorleap_instances_masks_encoder validation failed: '
589
- f'Unsupported return type. Should be a numpy array. Got {type(result)}.')
637
+ f'Unsupported return type. Should be a ElementInstance or None. Got {type(result)}.')
638
+
639
+ def inner_without_validate(sample_id, preprocess_response, instance_id):
640
+ global _called_from_inside_tl_decorator
641
+ _called_from_inside_tl_decorator += 1
642
+
643
+ try:
644
+ result = user_function(sample_id, preprocess_response, instance_id)
645
+ finally:
646
+ _called_from_inside_tl_decorator -= 1
647
+
648
+ return result
649
+
650
+ leap_binder.set_instance_masks(inner_without_validate, name)
651
+
652
+ def inner(sample_id, preprocess_response, instance_id):
653
+ if os.environ.get(mapping_runtime_mode_env_var_mame):
654
+ return None
655
+
656
+ _validate_input_args(sample_id, preprocess_response, instance_id)
657
+
658
+ result = inner_without_validate(sample_id, preprocess_response, instance_id)
659
+
660
+ _validate_result(result)
661
+ return result
662
+
663
+ return inner
664
+
665
+ return decorating_function
666
+
667
+ def tensorleap_instances_length_encoder(name: str):
668
+ def decorating_function(user_function: InstanceLengthCallableInterface):
669
+ def _validate_input_args(sample_id: str, preprocess_response: PreprocessResponse):
670
+ assert isinstance(sample_id, str), \
671
+ (f'tensorleap_instances_length_encoder validation failed: '
672
+ f'Argument sample_id should be str. Got {type(sample_id)}.')
673
+ assert isinstance(preprocess_response, PreprocessResponse), \
674
+ (f'tensorleap_instances_length_encoder validation failed: '
675
+ f'Argument preprocess_response should be a PreprocessResponse. Got {type(preprocess_response)}.')
676
+ assert type(sample_id) == preprocess_response.sample_id_type, \
677
+ (f'tensorleap_instances_length_encoder validation failed: '
678
+ f'Argument sample_id should be as the same type as defined in the preprocess response '
679
+ f'{preprocess_response.sample_id_type}. Got {type(sample_id)}.')
680
+
681
+ def _validate_result(result):
682
+ assert isinstance(result, int), \
683
+ (f'tensorleap_instances_length_encoder validation failed: '
684
+ f'Unsupported return type. Should be a int. Got {type(result)}.')
590
685
 
591
686
  def inner_without_validate(sample_id, preprocess_response):
592
687
  global _called_from_inside_tl_decorator
@@ -599,7 +694,7 @@ def tensorleap_instances_masks_encoder(name: str):
599
694
 
600
695
  return result
601
696
 
602
- leap_binder.set_instance_masks(inner_without_validate, name)
697
+ # leap_binder.set_instance_masks(inner_without_validate, name). # TODO: do i need this?
603
698
 
604
699
  def inner(sample_id, preprocess_response):
605
700
  if os.environ.get(mapping_runtime_mode_env_var_mame):
@@ -616,7 +711,6 @@ def tensorleap_instances_masks_encoder(name: str):
616
711
 
617
712
  return decorating_function
618
713
 
619
-
620
714
  def tensorleap_input_encoder(name: str, channel_dim=-1, model_input_index=None):
621
715
  def decorating_function(user_function: SectionCallableInterface):
622
716
  for input_handler in leap_binder.setup_container.inputs:
@@ -626,8 +720,6 @@ def tensorleap_input_encoder(name: str, channel_dim=-1, model_input_index=None):
626
720
  if channel_dim <= 0 and channel_dim != -1:
627
721
  raise Exception(f"Channel dim for input {name} is expected to be either -1 or positive")
628
722
 
629
- leap_binder.set_input(user_function, name, channel_dim=channel_dim)
630
-
631
723
  def _validate_input_args(sample_id: Union[int, str], preprocess_response: PreprocessResponse):
632
724
  assert isinstance(sample_id, (int, str)), \
633
725
  (f'tensorleap_input_encoder validation failed: '
@@ -650,15 +742,35 @@ def tensorleap_input_encoder(name: str, channel_dim=-1, model_input_index=None):
650
742
  assert channel_dim - 1 <= len(result.shape), (f'tensorleap_input_encoder validation failed: '
651
743
  f'The channel_dim ({channel_dim}) should be <= to the rank of the resulting input rank ({len(result.shape)}).')
652
744
 
745
+ def inner_without_validate(sample_id, preprocess_response):
746
+
747
+ global _called_from_inside_tl_decorator
748
+ _called_from_inside_tl_decorator += 1
749
+
750
+ try:
751
+ result = user_function(sample_id, preprocess_response)
752
+ finally:
753
+ _called_from_inside_tl_decorator -= 1
754
+
755
+ return result
756
+
757
+ leap_binder.set_input(inner_without_validate, name, channel_dim=channel_dim)
758
+
759
+
653
760
  def inner(sample_id, preprocess_response):
654
761
  _validate_input_args(sample_id, preprocess_response)
655
- result = user_function(sample_id, preprocess_response)
762
+
763
+ result = inner_without_validate(sample_id, preprocess_response)
764
+
656
765
  _validate_result(result)
657
766
 
658
767
  if _called_from_inside_tl_decorator == 0:
659
768
  result = np.expand_dims(result, axis=0)
769
+
660
770
  return result
661
771
 
772
+
773
+
662
774
  node_mapping_type = NodeMappingType.Input
663
775
  if model_input_index is not None:
664
776
  node_mapping_type = NodeMappingType(f'Input{str(model_input_index)}')
@@ -695,8 +807,6 @@ def tensorleap_gt_encoder(name: str):
695
807
  raise Exception(f'GT with name {name} already exists. '
696
808
  f'Please choose another')
697
809
 
698
- leap_binder.set_ground_truth(user_function, name)
699
-
700
810
  def _validate_input_args(sample_id: Union[int, str], preprocess_response: PreprocessResponse):
701
811
  assert isinstance(sample_id, (int, str)), \
702
812
  (f'tensorleap_gt_encoder validation failed: '
@@ -717,13 +827,30 @@ def tensorleap_gt_encoder(name: str):
717
827
  (f'tensorleap_gt_encoder validation failed: '
718
828
  f'The return type should be a numpy array of type float32. Got {result.dtype}.')
719
829
 
830
+ def inner_without_validate(sample_id, preprocess_response):
831
+ global _called_from_inside_tl_decorator
832
+ _called_from_inside_tl_decorator += 1
833
+
834
+ try:
835
+ result = user_function(sample_id, preprocess_response)
836
+ finally:
837
+ _called_from_inside_tl_decorator -= 1
838
+
839
+ return result
840
+
841
+ leap_binder.set_ground_truth(inner_without_validate, name)
842
+
843
+
720
844
  def inner(sample_id, preprocess_response):
721
845
  _validate_input_args(sample_id, preprocess_response)
722
- result = user_function(sample_id, preprocess_response)
846
+
847
+ result = inner_without_validate(sample_id, preprocess_response)
848
+
723
849
  _validate_result(result)
724
850
 
725
851
  if _called_from_inside_tl_decorator == 0:
726
852
  result = np.expand_dims(result, axis=0)
853
+
727
854
  return result
728
855
 
729
856
  inner.node_mapping = NodeMapping(name, NodeMappingType.GroundTruth)
@@ -760,14 +887,8 @@ def tensorleap_custom_loss(name: str, connects_to=None):
760
887
  f'Please choose another')
761
888
 
762
889
  valid_types = (np.ndarray, SamplePreprocessResponse)
763
- try:
764
- import tensorflow as tf
765
- valid_types = (np.ndarray, SamplePreprocessResponse, tf.Tensor)
766
- except ImportError:
767
- pass
768
890
 
769
891
  def _validate_input_args(*args, **kwargs):
770
-
771
892
  for i, arg in enumerate(args):
772
893
  if isinstance(arg, list):
773
894
  for y, elem in enumerate(arg):
@@ -786,10 +907,11 @@ def tensorleap_custom_loss(name: str, connects_to=None):
786
907
  f'Argument #{_arg_name} should be a numpy array. Got {type(arg)}.')
787
908
 
788
909
  def _validate_result(result):
789
- assert isinstance(result, valid_types), \
910
+ assert isinstance(result, np.ndarray), \
790
911
  (f'tensorleap_custom_loss validation failed: '
791
912
  f'The return type should be a numpy array. Got {type(result)}.')
792
913
 
914
+
793
915
  @functools.wraps(user_function)
794
916
  def inner_without_validate(*args, **kwargs):
795
917
  global _called_from_inside_tl_decorator
code_loader/leaploader.py CHANGED
@@ -16,7 +16,7 @@ from code_loader.contract.datasetclasses import DatasetSample, DatasetBaseHandle
16
16
  PreprocessResponse, VisualizerHandler, LeapData, \
17
17
  PredictionTypeHandler, MetadataHandler, CustomLayerHandler, MetricHandler, VisualizerHandlerData, MetricHandlerData, \
18
18
  MetricCallableReturnType, CustomLossHandlerData, CustomLossHandler, RawInputsForHeatmap, SamplePreprocessResponse, \
19
- ElementInstance
19
+ ElementInstance, custom_latent_space_attribute
20
20
  from code_loader.contract.enums import DataStateEnum, TestingSectionEnum, DataStateType, DatasetMetadataType
21
21
  from code_loader.contract.exceptions import DatasetScriptException
22
22
  from code_loader.contract.responsedataclasses import DatasetIntegParseResult, DatasetTestResultPayload, \
@@ -34,7 +34,7 @@ class LeapLoader(LeapLoaderBase):
34
34
  super().__init__(code_path, code_entry_name)
35
35
 
36
36
  self._preprocess_result_cached = None
37
-
37
+
38
38
  try:
39
39
  from code_loader.mixpanel_tracker import track_code_loader_loaded
40
40
  track_code_loader_loaded({
@@ -77,6 +77,8 @@ class LeapLoader(LeapLoaderBase):
77
77
  file_path = Path(self.code_path, self.code_entry_name)
78
78
  append_path_recursively(str(file_path))
79
79
 
80
+ importlib.invalidate_caches()
81
+
80
82
  spec = importlib.util.spec_from_file_location(self.code_path, file_path)
81
83
  if spec is None or spec.loader is None:
82
84
  raise DatasetScriptException(f'Something is went wrong with spec file from: {file_path}')
@@ -155,37 +157,32 @@ class LeapLoader(LeapLoaderBase):
155
157
  for prediction_type in setup.prediction_types
156
158
  }
157
159
 
158
- def get_sample(self, state: DataStateEnum, sample_id: Union[int, str]) -> DatasetSample:
160
+ def get_sample(self, state: DataStateEnum, sample_id: Union[int, str], instance_id: int = None) -> DatasetSample:
159
161
  self.exec_script()
160
162
  preprocess_result = self._preprocess_result()
161
163
  if state == DataStateEnum.unlabeled and sample_id not in preprocess_result[state].sample_ids:
162
164
  self._preprocess_result(update_unlabeled_preprocess=True)
163
165
 
164
166
  metadata, metadata_is_none = self._get_metadata(state, sample_id)
165
- sample = DatasetSample(inputs=self._get_inputs(state, sample_id),
166
- gt=None if state == DataStateEnum.unlabeled else self._get_gt(state, sample_id),
167
- metadata=metadata,
168
- metadata_is_none=metadata_is_none,
169
- index=sample_id,
170
- state=state)
171
- return sample
172
167
 
173
- def get_sample_with_masks(self, state: DataStateEnum, sample_id: Union[int, str]) -> DatasetSample:
174
- self.exec_script()
175
- preprocess_result = self._preprocess_result()
176
- if state == DataStateEnum.unlabeled and sample_id not in preprocess_result[state].sample_ids:
177
- self._preprocess_result(update_unlabeled_preprocess=True)
168
+ custom_latent_space = None
169
+ if global_leap_binder.setup_container.custom_latent_space is not None:
170
+ custom_latent_space = global_leap_binder.setup_container.custom_latent_space.function(sample_id,
171
+ preprocess_result[
172
+ state])
178
173
 
179
- metadata, metadata_is_none = self._get_metadata(state, sample_id)
174
+ instance_mask = self._get_instances_masks(state, sample_id, instance_id)
180
175
  sample = DatasetSample(inputs=self._get_inputs(state, sample_id),
181
176
  gt=None if state == DataStateEnum.unlabeled else self._get_gt(state, sample_id),
182
177
  metadata=metadata,
183
178
  metadata_is_none=metadata_is_none,
184
179
  index=sample_id,
185
180
  state=state,
186
- instance_masks=self._get_instances_masks(state, sample_id))
181
+ custom_latent_space=custom_latent_space,
182
+ instance_masks = instance_mask)
187
183
  return sample
188
184
 
185
+
189
186
  def check_dataset(self) -> DatasetIntegParseResult:
190
187
  test_payloads: List[DatasetTestResultPayload] = []
191
188
  setup_response = None
@@ -210,8 +207,6 @@ class LeapLoader(LeapLoaderBase):
210
207
  general_error = f"Something went wrong. {repr(e.__cause__)} in file {file_name}, line_number: {line_number}\nStacktrace:\n{stacktrace}"
211
208
  is_valid = False
212
209
 
213
-
214
-
215
210
  print_log = stdout_steam.getvalue()
216
211
  is_valid_for_model = bool(global_leap_binder.setup_container.custom_layers)
217
212
  model_setup = self.get_model_setup_response()
@@ -476,12 +471,14 @@ class LeapLoader(LeapLoaderBase):
476
471
  def _get_inputs(self, state: DataStateEnum, sample_id: Union[int, str]) -> Dict[str, npt.NDArray[np.float32]]:
477
472
  return self._get_dataset_handlers(global_leap_binder.setup_container.inputs, state, sample_id)
478
473
 
479
- def _get_instances_masks(self, state: DataStateEnum, sample_id: Union[int, str]) -> Dict[str, List[ElementInstance]]:
474
+ def _get_instances_masks(self, state: DataStateEnum, sample_id: Union[int, str], instance_id: int) -> Optional[Dict[str, ElementInstance]]:
475
+ if instance_id is None:
476
+ return None
480
477
  preprocess_result = self._preprocess_result()
481
478
  preprocess_state = preprocess_result[state]
482
479
  result_agg = {}
483
480
  for handler in global_leap_binder.setup_container.instance_masks:
484
- handler_result = handler.function(sample_id, preprocess_state)
481
+ handler_result = handler.function(sample_id, preprocess_state, instance_id)
485
482
  handler_name = handler.name
486
483
  result_agg[handler_name] = handler_result
487
484
  return result_agg
@@ -526,7 +523,8 @@ class LeapLoader(LeapLoaderBase):
526
523
 
527
524
  return converted_value, is_none
528
525
 
529
- def _get_metadata(self, state: DataStateEnum, sample_id: Union[int, str]) -> Tuple[Dict[str, Union[str, int, bool, float]], Dict[str, bool]]:
526
+ def _get_metadata(self, state: DataStateEnum, sample_id: Union[int, str]) -> Tuple[
527
+ Dict[str, Union[str, int, bool, float]], Dict[str, bool]]:
530
528
  result_agg = {}
531
529
  is_none = {}
532
530
  preprocess_result = self._preprocess_result()
@@ -555,7 +553,12 @@ class LeapLoader(LeapLoaderBase):
555
553
 
556
554
  return id_type
557
555
 
558
- def get_instances_data(self, state: DataStateEnum) -> Tuple[Dict[str, List[str]], Dict[str, str], Dict[str, str]]:
556
+ @lru_cache()
557
+ def has_custom_latent_space_decorator(self) -> bool:
558
+ self.exec_script()
559
+ return global_leap_binder.setup_container.custom_latent_space is not None
560
+
561
+ def get_instances_data(self, state: DataStateEnum) -> Tuple[Dict[str, List[str]], Dict[str, str]]:
559
562
  """
560
563
  This Method get the data state and returns two dictionaries that holds the mapping of the sample ids to their
561
564
  instances and the other way around and the sample ids array.
@@ -568,4 +571,4 @@ class LeapLoader(LeapLoaderBase):
568
571
  """
569
572
  preprocess_result = self._preprocess_result()
570
573
  preprocess_state = preprocess_result[state]
571
- return preprocess_state.sample_ids_to_instance_mappings, preprocess_state.instance_to_sample_ids_mappings, preprocess_state.instance_ids_to_names
574
+ return preprocess_state.sample_ids_to_instance_mappings, preprocess_state.instance_to_sample_ids_mappings
@@ -65,11 +65,7 @@ class LeapLoaderBase:
65
65
  pass
66
66
 
67
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[str, List[str]], Dict[str, str], Dict[str, str]]:
68
+ def get_instances_data(self, state: DataStateEnum) -> Tuple[Dict[str, List[str]], Dict[str, str]]:
73
69
  pass
74
70
 
75
71
  @abstractmethod
@@ -114,6 +110,10 @@ class LeapLoaderBase:
114
110
  def get_sample_id_type(self) -> Type:
115
111
  pass
116
112
 
113
+ @abstractmethod
114
+ def has_custom_latent_space_decorator(self) -> bool:
115
+ pass
116
+
117
117
  @abstractmethod
118
118
  def get_heatmap_visualizer_raw_vis_input_arg_name(self, visualizer_name: str) -> Optional[str]:
119
119
  pass
@@ -94,10 +94,6 @@ class MixpanelTracker:
94
94
  Args:
95
95
  event_properties: Optional additional properties to include in the event
96
96
  """
97
-
98
- if os.environ.get('IS_TENSORLEAP_PLATFORM') == 'true':
99
- return
100
-
101
97
  try:
102
98
  distinct_id = self._get_distinct_id()
103
99
 
@@ -110,8 +106,6 @@ class MixpanelTracker:
110
106
  '$device_id': device_id, # Always use device_id for $device_id
111
107
  'python_version': f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
112
108
  'platform': os.name,
113
- 'code_loader_version': '1.0',
114
- 'is_tensorleap_platform': os.environ.get('IS_TENSORLEAP_PLATFORM'),
115
109
  }
116
110
 
117
111
  if tensorleap_user_id:
code_loader/utils.py CHANGED
@@ -18,12 +18,12 @@ def to_numpy_return_wrapper(encoder_function: SectionCallableInterface) -> Secti
18
18
 
19
19
  return numpy_encoder_function
20
20
 
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)
21
+ def to_numpy_return_masks_wrapper(encoder_function: InstanceCallableInterface) -> InstanceCallableInterface:
22
+ def numpy_encoder_function(idx: Union[int, str], samples: PreprocessResponse, element_idx: Union[int, str]) -> Union[ElementInstance, None]:
23
+ result = encoder_function(idx, samples, element_idx)
24
+ if result is None:
25
+ return None
26
+ result.mask = np.array(result.mask)
27
27
  return result
28
28
  return numpy_encoder_function
29
29
 
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 TensorLeap
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,7 +1,8 @@
1
- Metadata-Version: 2.3
1
+ Metadata-Version: 2.1
2
2
  Name: code-loader
3
- Version: 1.0.119rc2
3
+ Version: 1.0.121
4
4
  Summary:
5
+ Home-page: https://github.com/tensorleap/code-loader
5
6
  License: MIT
6
7
  Author: dorhar
7
8
  Author-email: doron.harnoy@tensorleap.ai
@@ -19,7 +20,6 @@ Requires-Dist: numpy (>=2.3.2,<3.0.0) ; python_version >= "3.11" and python_vers
19
20
  Requires-Dist: psutil (>=5.9.5,<6.0.0)
20
21
  Requires-Dist: pyyaml (>=6.0.2,<7.0.0)
21
22
  Requires-Dist: requests (>=2.32.3,<3.0.0)
22
- Project-URL: Homepage, https://github.com/tensorleap/code-loader
23
23
  Project-URL: Repository, https://github.com/tensorleap/code-loader
24
24
  Description-Content-Type: text/markdown
25
25
 
@@ -1,6 +1,7 @@
1
+ LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
1
2
  code_loader/__init__.py,sha256=outxRQ0M-zMfV0QGVJmAed5qWfRmyD0TV6-goEGAzBw,406
2
3
  code_loader/contract/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
- code_loader/contract/datasetclasses.py,sha256=gJsXu4zVAaiBlq6GJwPxfTD2e0gICTtI_6Ir61MRL48,8838
4
+ code_loader/contract/datasetclasses.py,sha256=u0gfDDy02skhFG3ejJOxqxCnykhAcBPGJfv8Bi4s9eQ,8966
4
5
  code_loader/contract/enums.py,sha256=GEFkvUMXnCNt-GOoz7NJ9ecQZ2PPDettJNOsxsiM0wk,1622
5
6
  code_loader/contract/exceptions.py,sha256=jWqu5i7t-0IG0jGRsKF4DjJdrsdpJjIYpUkN1F4RiyQ,51
6
7
  code_loader/contract/mapping.py,sha256=e11h_sprwOyE32PcqgRq9JvyahQrPzwqgkhmbQLKLQY,1165
@@ -19,18 +20,18 @@ code_loader/experiment_api/types.py,sha256=MY8xFARHwdVA7p4dxyhD60ShmttgTvb4qdp1o
19
20
  code_loader/experiment_api/utils.py,sha256=XZHtxge12TS4H4-8PjV3sKuhp8Ud6ojAiIzTZJEqBqc,3304
20
21
  code_loader/experiment_api/workingspace_config_utils.py,sha256=DLzXQCg4dgTV_YgaSbeTVzq-2ja_SQw4zi7LXwKL9cY,990
21
22
  code_loader/inner_leap_binder/__init__.py,sha256=koOlJyMNYzGbEsoIbXathSmQ-L38N_pEXH_HvL7beXU,99
22
- code_loader/inner_leap_binder/leapbinder.py,sha256=0iHVHxC2NjfH7F0vQFVGy1e0llgKEyUHUHh3DdtqL70,32602
23
- code_loader/inner_leap_binder/leapbinder_decorators.py,sha256=wjtk3TflrjJ8Y-OeuedVBD-09ZuOjIKGUjL7sMBU0fQ,41017
24
- code_loader/leaploader.py,sha256=rQRK1lyUPSpZiRs6lKUUxVJBCe3grEY_UxEMxSIpuxI,29709
25
- code_loader/leaploaderbase.py,sha256=lKdw2pd6H9hFsxVmc7jJMoZd_vlG5He1ooqT-cR_yq8,4496
26
- code_loader/mixpanel_tracker.py,sha256=b4yUE-F_lVeq5JlGjcbTCpdDVL34qYCC3WCElmeisEU,4865
23
+ code_loader/inner_leap_binder/leapbinder.py,sha256=Q3D9yVM-GNEJfYRFvMV__BoZbcWOgnWKhrZXAv6Tu7o,33232
24
+ code_loader/inner_leap_binder/leapbinder_decorators.py,sha256=h_BTxp7kW71Wa60OfXBSTGaXvqZyZECtfCdC3j95_zw,45820
25
+ code_loader/leaploader.py,sha256=e7oaxXuqNUWvon5h32pzzv7iHxpUbsVnQRWu9VgdTUc,29751
26
+ code_loader/leaploaderbase.py,sha256=fFq9q8KM1wR9TsIfkdAkGKdz_Ss1JZmLIloMLaBAinQ,4433
27
+ code_loader/mixpanel_tracker.py,sha256=U20vQXH8G7XIVXxcpQcVEZSuIwwGnyH5RMHXWZZG8HI,4639
27
28
  code_loader/plot_functions/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
28
29
  code_loader/plot_functions/plot_functions.py,sha256=xg6Gi4myTN9crq6JtyrhYI38HLXjPVJcbnI7CIy8f7w,14625
29
30
  code_loader/plot_functions/visualize.py,sha256=gsBAYYkwMh7jIpJeDMPS8G4CW-pxwx6LznoQIvi4vpo,657
30
- code_loader/utils.py,sha256=_j8b60pimoNAvWMRj7hEkkT6C76qES6cZoBFHpXHMxA,2698
31
+ code_loader/utils.py,sha256=i1KOchLkieHfaVz6YskSIfKA45HcqAmGAK1F2Kcg38c,2724
31
32
  code_loader/visualizers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
32
33
  code_loader/visualizers/default_visualizers.py,sha256=onRnLE_TXfgLN4o52hQIOOhUcFexGlqJ3xSpQDVLuZM,2604
33
- code_loader-1.0.119rc2.dist-info/LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
34
- code_loader-1.0.119rc2.dist-info/METADATA,sha256=HFzUxae_sRJJHFJrzIVEKtpSCai_c8H4kbpDcxnrLOs,1105
35
- code_loader-1.0.119rc2.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
36
- code_loader-1.0.119rc2.dist-info/RECORD,,
34
+ code_loader-1.0.121.dist-info/LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
35
+ code_loader-1.0.121.dist-info/METADATA,sha256=mo_wEQJ-RufJvuLWjZtzhwFEu_JzP6jM1eRTHfkYMu0,1090
36
+ code_loader-1.0.121.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
37
+ code_loader-1.0.121.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: poetry-core 2.1.3
2
+ Generator: poetry-core 1.9.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
File without changes