code-loader 1.0.29__tar.gz → 1.0.38.dev6__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. {code_loader-1.0.29 → code_loader-1.0.38.dev6}/PKG-INFO +1 -1
  2. {code_loader-1.0.29 → code_loader-1.0.38.dev6}/code_loader/contract/datasetclasses.py +13 -4
  3. {code_loader-1.0.29 → code_loader-1.0.38.dev6}/code_loader/contract/enums.py +6 -0
  4. {code_loader-1.0.29 → code_loader-1.0.38.dev6}/code_loader/contract/responsedataclasses.py +2 -0
  5. {code_loader-1.0.29 → code_loader-1.0.38.dev6}/code_loader/contract/visualizer_classes.py +20 -1
  6. {code_loader-1.0.29 → code_loader-1.0.38.dev6}/code_loader/inner_leap_binder/leapbinder.py +24 -11
  7. {code_loader-1.0.29 → code_loader-1.0.38.dev6}/code_loader/leaploader.py +1 -1
  8. {code_loader-1.0.29 → code_loader-1.0.38.dev6}/code_loader/visualizers/default_visualizers.py +12 -2
  9. {code_loader-1.0.29 → code_loader-1.0.38.dev6}/pyproject.toml +1 -1
  10. code_loader-1.0.29/code_loader/code_inegration_processes_manager.py +0 -83
  11. {code_loader-1.0.29 → code_loader-1.0.38.dev6}/LICENSE +0 -0
  12. {code_loader-1.0.29 → code_loader-1.0.38.dev6}/README.md +0 -0
  13. {code_loader-1.0.29 → code_loader-1.0.38.dev6}/code_loader/__init__.py +0 -0
  14. {code_loader-1.0.29 → code_loader-1.0.38.dev6}/code_loader/contract/__init__.py +0 -0
  15. {code_loader-1.0.29 → code_loader-1.0.38.dev6}/code_loader/contract/exceptions.py +0 -0
  16. {code_loader-1.0.29 → code_loader-1.0.38.dev6}/code_loader/inner_leap_binder/__init__.py +0 -0
  17. {code_loader-1.0.29 → code_loader-1.0.38.dev6}/code_loader/utils.py +0 -0
  18. {code_loader-1.0.29 → code_loader-1.0.38.dev6}/code_loader/visualizers/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: code-loader
3
- Version: 1.0.29
3
+ Version: 1.0.38.dev6
4
4
  Summary:
5
5
  Home-page: https://github.com/tensorleap/code-loader
6
6
  License: MIT
@@ -4,9 +4,11 @@ from typing import Any, Callable, List, Optional, Dict, Union, Type
4
4
  import numpy as np
5
5
  import numpy.typing as npt
6
6
 
7
- from code_loader.contract.enums import DataStateType, DataStateEnum, LeapDataType, ConfusionMatrixValue
7
+ from code_loader.contract.enums import DataStateType, DataStateEnum, LeapDataType, ConfusionMatrixValue, MetricDirection
8
8
  from code_loader.contract.visualizer_classes import LeapImage, LeapText, LeapGraph, LeapHorizontalBar, \
9
- LeapTextMask, LeapImageMask, LeapImageWithBBox
9
+ LeapTextMask, LeapImageMask, LeapImageWithBBox, LeapImageWithHeatmap
10
+
11
+ custom_latent_space_attribute = "custom_latent_space"
10
12
 
11
13
 
12
14
  @dataclass
@@ -48,11 +50,12 @@ VisualizerCallableInterface = Union[
48
50
  Callable[..., LeapHorizontalBar],
49
51
  Callable[..., LeapImageMask],
50
52
  Callable[..., LeapTextMask],
51
- Callable[..., LeapImageWithBBox]
53
+ Callable[..., LeapImageWithBBox],
54
+ Callable[..., LeapImageWithHeatmap]
52
55
  ]
53
56
 
54
57
  VisualizerCallableReturnType = Union[LeapImage, LeapText, LeapGraph, LeapHorizontalBar,
55
- LeapImageMask, LeapTextMask, LeapImageWithBBox]
58
+ LeapImageMask, LeapTextMask, LeapImageWithBBox, LeapImageWithHeatmap]
56
59
 
57
60
  CustomCallableInterface = Callable[..., Any]
58
61
 
@@ -85,6 +88,11 @@ class MetricHandler:
85
88
  name: str
86
89
  function: Union[CustomCallableInterfaceMultiArgs, ConfusionMatrixCallableInterfaceMultiArgs]
87
90
  arg_names: List[str]
91
+ direction: Optional[MetricDirection] = MetricDirection.Downward
92
+
93
+ @dataclass
94
+ class RawInputsForHeatmap:
95
+ raw_input_by_vizualizer_arg_name: Dict[str, npt.NDArray[np.float32]]
88
96
 
89
97
 
90
98
  @dataclass
@@ -131,6 +139,7 @@ class CustomLayerHandler:
131
139
  layer: Type[Any]
132
140
  init_arg_names: List[str]
133
141
  call_arg_names: List[str]
142
+ use_custom_latent_space: bool = False
134
143
 
135
144
 
136
145
  @dataclass
@@ -26,6 +26,12 @@ class LeapDataType(Enum):
26
26
  ImageMask = 'ImageMask'
27
27
  TextMask = 'TextMask'
28
28
  ImageWithBBox = 'ImageWithBBox'
29
+ ImageWithHeatmap = 'ImageWithHeatmap'
30
+
31
+
32
+ class MetricDirection(Enum):
33
+ Upward = "Upward"
34
+ Downward = "Downward"
29
35
 
30
36
 
31
37
  class DatasetMetadataType(Enum):
@@ -56,6 +56,7 @@ class CustomLayerInstance:
56
56
  name: str
57
57
  init_arg_names: List[str]
58
58
  call_arg_names: List[str]
59
+ use_custom_latent_space: bool = False
59
60
 
60
61
 
61
62
  @dataclass
@@ -102,6 +103,7 @@ class BoundingBox:
102
103
  height: float # value between [0, 1], represent the percentage according to the image size.
103
104
  confidence: float
104
105
  label: str
106
+ rotation: float = 0.0 # value between [0, 360], represent the degree of rotation.
105
107
 
106
108
 
107
109
  @dataclass
@@ -135,6 +135,24 @@ class LeapTextMask:
135
135
  validate_type(type(label), str)
136
136
 
137
137
 
138
+ @dataclass
139
+ class LeapImageWithHeatmap:
140
+ image: npt.NDArray[np.float32]
141
+ heatmaps: npt.NDArray[np.float32]
142
+ labels: List[str]
143
+ type: LeapDataType = LeapDataType.ImageWithHeatmap
144
+
145
+ def __post_init__(self) -> None:
146
+ validate_type(self.type, LeapDataType.ImageWithHeatmap)
147
+ validate_type(type(self.heatmaps), np.ndarray)
148
+ validate_type(self.heatmaps.dtype, np.float32)
149
+ validate_type(type(self.image), np.ndarray)
150
+ validate_type(self.image.dtype, np.float32)
151
+ validate_type(type(self.labels), list)
152
+ for label in self.labels:
153
+ validate_type(type(label), str)
154
+
155
+
138
156
  map_leap_data_type_to_visualizer_class = {
139
157
  LeapDataType.Image.value: LeapImage,
140
158
  LeapDataType.Graph.value: LeapGraph,
@@ -142,5 +160,6 @@ map_leap_data_type_to_visualizer_class = {
142
160
  LeapDataType.HorizontalBar.value: LeapHorizontalBar,
143
161
  LeapDataType.ImageMask.value: LeapImageMask,
144
162
  LeapDataType.TextMask.value: LeapTextMask,
145
- LeapDataType.ImageWithBBox.value: LeapImageWithBBox
163
+ LeapDataType.ImageWithBBox.value: LeapImageWithBBox,
164
+ LeapDataType.ImageWithHeatmap.value: LeapImageWithHeatmap
146
165
  }
@@ -9,15 +9,15 @@ from code_loader.contract.datasetclasses import SectionCallableInterface, InputH
9
9
  PreprocessHandler, VisualizerCallableInterface, CustomLossHandler, CustomCallableInterface, PredictionTypeHandler, \
10
10
  MetadataSectionCallableInterface, UnlabeledDataPreprocessHandler, CustomLayerHandler, MetricHandler, \
11
11
  CustomCallableInterfaceMultiArgs, ConfusionMatrixCallableInterfaceMultiArgs, VisualizerCallableReturnType, \
12
- CustomMultipleReturnCallableInterfaceMultiArgs, DatasetBaseHandler
13
- from code_loader.contract.enums import LeapDataType, DataStateEnum, DataStateType
12
+ CustomMultipleReturnCallableInterfaceMultiArgs, DatasetBaseHandler, custom_latent_space_attribute, RawInputsForHeatmap
13
+ from code_loader.contract.enums import LeapDataType, DataStateEnum, DataStateType, MetricDirection
14
14
  from code_loader.contract.responsedataclasses import DatasetTestResultPayload
15
15
  from code_loader.contract.visualizer_classes import map_leap_data_type_to_visualizer_class
16
16
  from code_loader.utils import to_numpy_return_wrapper, get_shape
17
17
  from code_loader.visualizers.default_visualizers import DefaultVisualizer, \
18
18
  default_graph_visualizer, \
19
19
  default_image_visualizer, default_horizontal_bar_visualizer, default_word_visualizer, \
20
- default_image_mask_visualizer, default_text_mask_visualizer, default_raw_data_visualizer
20
+ default_image_mask_visualizer, default_text_mask_visualizer, default_raw_data_visualizer, default_image_heatmap_visualizer
21
21
 
22
22
 
23
23
  class LeapBinder:
@@ -31,6 +31,8 @@ class LeapBinder:
31
31
  def _extend_with_default_visualizers(self) -> None:
32
32
  self.set_visualizer(function=default_image_visualizer, name=DefaultVisualizer.Image.value,
33
33
  visualizer_type=LeapDataType.Image)
34
+ self.set_visualizer(function=default_image_heatmap_visualizer, name=DefaultVisualizer.ImageHeatmap.value,
35
+ visualizer_type=LeapDataType.ImageWithHeatmap)
34
36
  self.set_visualizer(function=default_graph_visualizer, name=DefaultVisualizer.Graph.value,
35
37
  visualizer_type=LeapDataType.Graph)
36
38
  self.set_visualizer(function=default_raw_data_visualizer, name=DefaultVisualizer.RawData.value,
@@ -50,10 +52,16 @@ class LeapBinder:
50
52
  heatmap_visualizer: Optional[Callable[..., npt.NDArray[np.float32]]] = None) -> None:
51
53
  arg_names = inspect.getfullargspec(function)[0]
52
54
  if heatmap_visualizer:
53
- if arg_names != inspect.getfullargspec(heatmap_visualizer)[0]:
54
- raise Exception(
55
- f'The argument names of the heatmap visualizer callback must match the visualizer callback '
56
- f'{str(arg_names)}')
55
+ visualizer_arg_names_set = set(arg_names)
56
+ heatmap_visualizer_inspection = inspect.getfullargspec(heatmap_visualizer)
57
+ heatmap_arg_names_set = set(heatmap_visualizer_inspection[0])
58
+ if visualizer_arg_names_set != heatmap_arg_names_set:
59
+ arg_names_difference = set(inspect.getfullargspec(heatmap_visualizer)[0]).difference(set(arg_names))
60
+ if len(arg_names_difference) != 1 or \
61
+ heatmap_visualizer_inspection.annotations[list(arg_names_difference)[0]] != RawInputsForHeatmap:
62
+ raise Exception(
63
+ f'The argument names of the heatmap visualizer callback must match the visualizer callback '
64
+ f'{str(arg_names)}')
57
65
 
58
66
  if visualizer_type.value not in map_leap_data_type_to_visualizer_class:
59
67
  raise Exception(
@@ -103,9 +111,10 @@ class LeapBinder:
103
111
  function: Union[CustomCallableInterfaceMultiArgs,
104
112
  CustomMultipleReturnCallableInterfaceMultiArgs,
105
113
  ConfusionMatrixCallableInterfaceMultiArgs],
106
- name: str) -> None:
114
+ name: str,
115
+ direction: Optional[MetricDirection] = MetricDirection.Downward) -> None:
107
116
  arg_names = inspect.getfullargspec(function)[0]
108
- self.setup_container.metrics.append(MetricHandler(name, function, arg_names))
117
+ self.setup_container.metrics.append(MetricHandler(name, function, arg_names, direction))
109
118
 
110
119
  def add_prediction(self, name: str, labels: List[str], channel_dim: int = -1) -> None:
111
120
  self.setup_container.prediction_types.append(PredictionTypeHandler(name, labels, channel_dim))
@@ -120,13 +129,17 @@ class LeapBinder:
120
129
  self.setup_container.metadata.append(MetadataHandler(name, function))
121
130
 
122
131
  def set_custom_layer(self, custom_layer: Type[Any], name: str, inspect_layer: bool = False,
123
- kernel_index: Optional[int] = None) -> None:
132
+ kernel_index: Optional[int] = None, use_custom_latent_space: bool = False) -> None:
124
133
  if inspect_layer and kernel_index is not None:
125
134
  custom_layer.kernel_index = kernel_index
126
135
 
136
+ if use_custom_latent_space and not hasattr(custom_layer, custom_latent_space_attribute):
137
+ raise Exception(f"{custom_latent_space_attribute} function has not been set for custom layer: {custom_layer.__name__}")
138
+
127
139
  init_args = inspect.getfullargspec(custom_layer.__init__)[0][1:]
128
140
  call_args = inspect.getfullargspec(custom_layer.call)[0][1:]
129
- self.setup_container.custom_layers[name] = CustomLayerHandler(name, custom_layer, init_args, call_args)
141
+ self.setup_container.custom_layers[name] = CustomLayerHandler(name, custom_layer, init_args, call_args,
142
+ use_custom_latent_space=use_custom_latent_space)
130
143
 
131
144
  def check_preprocess(self, preprocess_result: Dict[DataStateEnum, PreprocessResponse]) -> None:
132
145
  preprocess_handler = self.setup_container.preprocess
@@ -274,7 +274,7 @@ class LeapLoader:
274
274
  setup = global_leap_binder.setup_container
275
275
  custom_layer_instances = [
276
276
  CustomLayerInstance(custom_layer_handler.name, custom_layer_handler.init_arg_names,
277
- custom_layer_handler.call_arg_names)
277
+ custom_layer_handler.call_arg_names, custom_layer_handler.use_custom_latent_space)
278
278
  for custom_layer_handler in setup.custom_layers.values()
279
279
  ]
280
280
  return ModelSetup(custom_layer_instances)
@@ -4,7 +4,7 @@ import numpy as np
4
4
  import numpy.typing as npt
5
5
 
6
6
  from code_loader.contract.visualizer_classes import LeapImage, LeapGraph, LeapHorizontalBar, LeapText, \
7
- LeapImageMask, LeapTextMask
7
+ LeapImageMask, LeapTextMask, LeapImageWithHeatmap
8
8
  from code_loader.utils import rescale_min_max
9
9
 
10
10
 
@@ -16,13 +16,23 @@ class DefaultVisualizer(Enum):
16
16
  ImageMask = 'ImageMask'
17
17
  TextMask = 'TextMask'
18
18
  RawData = 'RawData'
19
-
19
+ ImageHeatmap = 'ImageHeatmap'
20
+
20
21
 
21
22
  def default_image_visualizer(data: npt.NDArray[np.float32]) -> LeapImage:
22
23
  rescaled_data = rescale_min_max(data)
23
24
  return LeapImage(rescaled_data)
24
25
 
25
26
 
27
+ def default_image_heatmap_visualizer(image: npt.NDArray[np.float32], heatmaps: npt.NDArray[np.float32], labels: list) -> LeapImageWithHeatmap:
28
+ rescaled_image = rescale_min_max(image)
29
+ rescaled_heatmaps = []
30
+ for heatmap in heatmaps:
31
+ rescaled_heatmap = rescale_min_max(heatmap)
32
+ rescaled_heatmaps = np.append(rescaled_heatmaps, rescaled_heatmap)
33
+ return LeapImageWithHeatmap(rescaled_image, rescaled_heatmaps, labels)
34
+
35
+
26
36
  def default_graph_visualizer(data: npt.NDArray[np.float32]) -> LeapGraph:
27
37
  return LeapGraph(data)
28
38
 
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "code-loader"
3
- version = "1.0.29"
3
+ version = "1.0.38.dev6"
4
4
  description = ""
5
5
  authors = ["dorhar <doron.harnoy@tensorleap.ai>"]
6
6
  license = "MIT"
@@ -1,83 +0,0 @@
1
- # mypy: ignore-errors
2
- import traceback
3
- from dataclasses import dataclass
4
-
5
- from typing import List, Tuple, Optional
6
-
7
- from multiprocessing import Process, Queue
8
-
9
- from code_loader.leap_loader_parallelized_base import LeapLoaderParallelizedBase
10
- from code_loader.leaploader import LeapLoader
11
- from code_loader.contract.enums import DataStateEnum
12
- from code_loader.metric_calculator_parallelized import MetricCalculatorParallelized
13
- from code_loader.samples_generator_parallelized import SamplesGeneratorParallelized
14
-
15
-
16
- @dataclass
17
- class SampleSerializableError:
18
- state: DataStateEnum
19
- index: int
20
- leap_script_trace: str
21
- exception_as_str: str
22
-
23
-
24
- class CodeIntegrationProcessesManager:
25
- def __init__(self, code_path: str, code_entry_name: str, n_workers: Optional[int] = 2,
26
- max_samples_in_queue: int = 128) -> None:
27
- self.metric_calculator_parallelized = MetricCalculatorParallelized(code_path, code_entry_name)
28
- self.samples_generator_parallelized = SamplesGeneratorParallelized(code_path, code_entry_name)
29
-
30
- def _create_and_start_process(self) -> Process:
31
- process = self.multiprocessing_context.Process(
32
- target=CodeIntegrationProcessesManager._process_func,
33
- args=(self.code_path, self.code_entry_name, self._inputs_waiting_to_be_process,
34
- self._ready_processed_results))
35
- process.daemon = True
36
- process.start()
37
- return process
38
-
39
- def _run_and_warm_first_process(self):
40
- process = self._create_and_start_process()
41
- self.processes = [process]
42
-
43
- # needed in order to make sure the preprocess func runs once in nonparallel
44
- self._start_process_inputs([(DataStateEnum.training, 0)])
45
- self._get_next_ready_processed_result()
46
-
47
- def _operation_decider(self):
48
- if self.metric_calculator_parallelized._ready_processed_results.empty() and not \
49
- self.metric_calculator_parallelized._inputs_waiting_to_be_process.empty():
50
- return 'metric'
51
-
52
- if self.samples_generator_parallelized._ready_processed_results.empty() and not \
53
- self.samples_generator_parallelized._inputs_waiting_to_be_process.empty():
54
- return 'dataset'
55
-
56
-
57
-
58
-
59
- @staticmethod
60
- def _process_func(code_path: str, code_entry_name: str,
61
- samples_to_process: Queue, ready_samples: Queue,
62
- metrics_to_process: Queue, ready_metrics: Queue) -> None:
63
- import os
64
- os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
65
-
66
- leap_loader = LeapLoader(code_path, code_entry_name)
67
- while True:
68
-
69
- # decide on sample or metric to process
70
- state, idx = samples_to_process.get(block=True)
71
- leap_loader._preprocess_result()
72
- try:
73
- sample = leap_loader.get_sample(state, idx)
74
- except Exception as e:
75
- leap_script_trace = traceback.format_exc().split('File "<string>"')[-1]
76
- ready_samples.put(SampleSerializableError(state, idx, leap_script_trace, str(e)))
77
- continue
78
-
79
- ready_samples.put(sample)
80
-
81
- def generate_samples(self, sample_identities: List[Tuple[DataStateEnum, int]]):
82
- return self.start_process_inputs(sample_identities)
83
-
File without changes