leap-model-parser 0.1.185.dev11__py3-none-any.whl → 0.1.187__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.
@@ -1,51 +1,12 @@
1
1
  from enum import Enum
2
2
  from typing import Optional, Dict, Any, List
3
3
 
4
- from code_loader.contract.mapping import NodeConnection, NodeMappingType, NodeMapping
5
- from keras import Model
4
+ from code_loader.contract.mapping import NodeConnection, NodeMappingType, NodeMapping # type: ignore
5
+ from keras import Model # type: ignore
6
6
 
7
7
  from leap_model_parser.contract.graph import Node as Node, OutputData, ConnectionOutput, ConnectionInput, InputData
8
8
 
9
9
 
10
- # class NodeMappingType(Enum):
11
- # Visualizer = 'Visualizer'
12
- # Metric = 'Metric'
13
- # GroundTruth = 'GroundTruth'
14
- # Input = 'Input'
15
- # Layer = 'Layer'
16
- # Loss = 'Loss'
17
- # CustomLoss = 'CustomLoss'
18
- # Optimizer = 'Optimizer'
19
- # Prediction0 = 'Prediction0'
20
- # Prediction1 = 'Prediction1'
21
- # Prediction2 = 'Prediction2'
22
- # Prediction3 = 'Prediction3'
23
- # Input0 = 'Input0'
24
- # Input1 = 'Input1'
25
- # Input2 = 'Input2'
26
- # Input3 = 'Input3'
27
- # Input4 = 'Input4'
28
- # Input5 = 'Input5'
29
- #
30
- #
31
- #
32
- #
33
- #
34
- # @dataclass
35
- # class NodeMapping:
36
- # name: str
37
- # type: NodeMappingType
38
- # user_unique_name: Optional[str] = None
39
- # sub_type: Optional[str] = None
40
- # arg_names: Optional[List[str]] = None
41
- #
42
- #
43
- # @dataclass
44
- # class NodeConnection:
45
- # node: NodeMapping
46
- # node_inputs: Optional[Dict[str, NodeMapping]]
47
- # prediction_type_name: Optional[str] = None
48
-
49
10
 
50
11
  class LeapGraphEditor:
51
12
  def __init__(self, model_graph: Dict[str, Node], keras_model: Model):
@@ -55,33 +16,21 @@ class LeapGraphEditor:
55
16
  node_ids_as_int = [int(node_id) for node_id in model_graph.keys()]
56
17
  self._next_node_id_index = max(node_ids_as_int) + 1
57
18
 
58
- # def add_dataset(self, dataset_name: str, raw_dataset_version: Dict[str, Any],
59
- # dataset_parse_result: DatasetIntegParseResult):
60
- #
61
- # LeapGraphEditor._add_setup_to_metadata(raw_dataset_version['metadata'], dataset_parse_result)
62
- # raw_dataset_version['name'] = dataset_name
63
- #
64
- # dataset_node = self._get_dataset_node()
65
- # dataset_node.data['datasetVersion'] = raw_dataset_version
66
- # dataset_node.data['selected_dataset'] = dataset_name
67
- # self._add_arg_names_to_visualizers(dataset_parse_result)
68
19
 
69
20
  def add_connections_to_graph(self, connections: List[NodeConnection]):
70
- connections = self._validate_and_reorder_connections_list(connections)
21
+ connections = self._replace_prediction_node_name_with_correct_name(connections)
71
22
  for connection in connections:
72
23
  self._add_node_connection_to_graph(connection)
73
24
 
74
25
  def _add_node_connection_to_graph(self, node_connection: NodeConnection):
75
- # if node_connection.node.type.value.startswith('Input'):
76
- # input_index = int(node_connection.node.type.value.replace('Input', ''))
77
- #
78
- # origin_name = self.keras_model.inputs[input_index].node.layer.name
79
- #
80
- # _find_node_by_origin_name
81
- # # elif node_connection.node.type == NodeMappingType.Input:
82
- # # self._find_or_add_input_node()
83
-
84
-
26
+ if node_connection.node.type == NodeMappingType.PredictionLabels:
27
+ prediction_labels_name = node_connection.node.name
28
+ prediction_node = list(node_connection.node_inputs.values())[0]
29
+ prediction_mapping_node = self._find_node_by_origin_name(prediction_node.name)
30
+ assert prediction_mapping_node is not None, \
31
+ f"Prediction node with name {prediction_node.name} not found in model graph"
32
+ prediction_node_id = prediction_mapping_node.id
33
+ self.model_graph[prediction_node_id].data['prediction_type'] = prediction_labels_name
85
34
  if node_connection.node.type == NodeMappingType.Visualizer:
86
35
  new_visualizer_node_id = self._add_visualizer_node(
87
36
  node_connection.node.name, node_connection.node.sub_type,
@@ -97,26 +46,12 @@ class LeapGraphEditor:
97
46
  input_node_id = self._find_or_add_input_node(node)
98
47
  self._add_connection_to_node(new_metric_node_id, input_name, input_node_id)
99
48
  elif node_connection.node.type in (NodeMappingType.Loss, NodeMappingType.CustomLoss):
100
- prediction_type_name = node_connection.prediction_type_name
101
- # if prediction_type_name is None:
102
- # raise Exception("prediction_type_name is required for loss connection")
103
-
104
49
  new_loss_node_id = self._add_loss_node(node_connection.node.name,
105
50
  node_connection.node.type == NodeMappingType.CustomLoss,
106
51
  node_connection.node.arg_names)
107
52
  for input_name, node in node_connection.node_inputs.items():
108
53
  input_node_id = self._find_or_add_input_node(node)
109
- # if node.type == NodeMappingType.Layer:
110
- # self.model_graph[input_node_id].data['prediction_type'] = prediction_type_name
111
54
  self._add_connection_to_node(new_loss_node_id, input_name, input_node_id)
112
- # elif node_connection.node.type == NodeMappingType.Optimizer:
113
- # new_optimizer_node_id = self._add_optimizer_node(node_connection.node.name)
114
- # loss_node_ids = self._get_all_loss_node_ids()
115
- # assert len(loss_node_ids) > 0
116
- # for i, loss_node_id in enumerate(loss_node_ids):
117
- # self._add_connection_to_node(new_optimizer_node_id, str(i), loss_node_id)
118
- # self.model_graph[new_optimizer_node_id].data['custom_input_keys'] = list(
119
- # self.model_graph[new_optimizer_node_id].inputs.keys())
120
55
  else:
121
56
  raise Exception(f"Can't add node of type {node_connection.node.type.name}")
122
57
 
@@ -140,30 +75,18 @@ class LeapGraphEditor:
140
75
  return node
141
76
  return None
142
77
 
143
- def _validate_and_reorder_connections_list(self, connections: List[NodeConnection]) -> List[NodeConnection]:
144
- # optimizers = [connection for connection in connections if connection.node.type == NodeType.Optimizer]
78
+ def _replace_prediction_node_name_with_correct_name(self, connections: List[NodeConnection]) -> List[NodeConnection]:
145
79
  for connection in connections:
146
80
  if connection.node_inputs is None:
147
81
  continue
148
82
  for input_name, input_node in connection.node_inputs.items():
149
83
  if 'Prediction' in input_node.type.value:
150
- prediction_index= int(input_node.type.value.replace('Prediction', ''))
84
+ prediction_index = int(input_node.type.value.replace('Prediction', ''))
151
85
  origin_name = self.keras_model.outputs[prediction_index].node.layer.name
152
86
  input_node.name = origin_name
153
87
 
154
88
  return connections
155
- losses = [connection for connection in connections
156
- if connection.node.type in (NodeMappingType.Loss, NodeMappingType.CustomLoss)]
157
- visualizers = [connection for connection in connections if connection.node.type == NodeMappingType.Visualizer]
158
89
 
159
- # if len(optimizers) == 0:
160
- # raise Exception('At least one optimizer needed')
161
- # if len(losses) == 0:
162
- # raise Exception('At least one loss needed')
163
- # if len(optimizers) + len(losses) + len(visualizers) < len(connections):
164
- # raise Exception('Unsupported node type')
165
-
166
- return visualizers + losses
167
90
 
168
91
  def _find_encoder_node_id(self, encoder_name: str) -> Optional[str]:
169
92
  for node_id, node_response in self.model_graph.items():
@@ -247,9 +170,6 @@ class LeapGraphEditor:
247
170
  outputs={
248
171
  f'{new_node_id}-loss': ConnectionOutput([])
249
172
  }
250
- # outputs={
251
- # f'{new_node_id}-loss': {'connections': []}
252
- # }
253
173
  )
254
174
  if arg_names is not None:
255
175
  loss_node.data['arg_names'] = arg_names
@@ -258,28 +178,12 @@ class LeapGraphEditor:
258
178
  self.model_graph[new_node_id] = loss_node
259
179
  return new_node_id
260
180
 
261
- # def _add_optimizer_node(self, optimizer_name: str) -> str:
262
- # new_node_id = self._generate_new_node_id()
263
- #
264
- # optimizer_node = NodeResponse(
265
- # new_node_id,
266
- # optimizer_name,
267
- # data={'type': 'Optimizer', 'selected': optimizer_name},
268
- # inputs={},
269
- # outputs={})
270
- #
271
- # self.model_graph[new_node_id] = optimizer_node
272
- # return new_node_id
273
-
274
181
  def _get_output_name_from_node_id(self, input_node_id: str, input_name: Optional[str] = None) -> str:
275
182
  input_node_outputs_len = len(self.model_graph[input_node_id].outputs)
276
183
  if input_node_outputs_len == 0:
277
184
  output_name_to_add = f'{input_node_id}-feature_map'
278
185
  self.model_graph[input_node_id].outputs[output_name_to_add] = ConnectionOutput([])
279
186
 
280
- # self.model_graph[input_node_id].outputs[output_name_to_add] = {
281
- # 'connections': []
282
- # }
283
187
  return output_name_to_add
284
188
  if input_node_outputs_len == 1:
285
189
  return list(self.model_graph[input_node_id].outputs.keys())[0]
@@ -296,16 +200,32 @@ class LeapGraphEditor:
296
200
  output_name = self._get_output_name_from_node_id(input_node_id, input_name)
297
201
  input_name = f'{node_id}-{input_name}'
298
202
  self.model_graph[node_id].inputs[input_name] = ConnectionInput([InputData(input_node_id, output_name)])
299
- # self.model_graph[node_id].inputs[input_name] = {
300
- # 'connections': [{'data': {}, 'node': input_node_id, 'output': output_name}]
301
- # }
302
203
 
303
- # if 'connections' not in self.model_graph[input_node_id].outputs[output_name]:
304
- # self.model_graph[input_node_id].outputs[output_name]['connections'] = []
305
204
  output_connection = OutputData(node_id, input_name)
306
- # output_connection = {'input': input_name, 'node': node_id, 'data': {}}
307
205
  self.model_graph[input_node_id].outputs[output_name].connections.append(output_connection)
308
206
 
207
+ def _handle_input_node_with_index(self, input_node: NodeMapping) -> str:
208
+ input_index = int(input_node.type.value.replace('Input', ''))
209
+ origin_name = self.keras_model.inputs[input_index].node.layer.name
210
+ input_node = self._find_input_node_by_origin_name(origin_name)
211
+ assert input_node is not None, f"Input node with origin name {origin_name} not found in model graph"
212
+ input_node_id = input_node.id
213
+ self.model_graph[input_node_id].data['output_name'] = input_node.name
214
+ output_keys = list(self.model_graph[input_node_id].outputs.keys())
215
+ for output_key in output_keys:
216
+ new_output_key = f'{input_node_id}-{input_node.name}'
217
+ if output_key == new_output_key:
218
+ continue
219
+ self.model_graph[input_node_id].outputs[new_output_key] = self.model_graph[input_node_id].outputs[
220
+ output_key]
221
+ del self.model_graph[input_node_id].outputs[output_key]
222
+ for connection in self.model_graph[input_node_id].outputs[new_output_key].connections:
223
+ for connection_input in self.model_graph[connection.node].inputs[connection.input].connections:
224
+ if connection_input.output == output_key:
225
+ connection_input.output = new_output_key
226
+
227
+ return input_node_id
228
+
309
229
  def _find_or_add_input_node(self, input_node: NodeMapping) -> str:
310
230
  if input_node.type in (NodeMappingType.Input, NodeMappingType.GroundTruth):
311
231
  input_node_id = self._find_encoder_node_id(input_node.name)
@@ -315,26 +235,12 @@ class LeapGraphEditor:
315
235
  else:
316
236
  raise Exception(f'Couldnt find input node name {input_node.name}')
317
237
  elif 'Input' in input_node.type.value:
318
- input_index = int(input_node.type.value.replace('Input', ''))
319
- origin_name = self.keras_model.inputs[input_index].node.layer.name
320
- input_node_id = self._find_input_node_by_origin_name(origin_name).id
321
- self.model_graph[input_node_id].data['output_name'] = input_node.name
322
- output_keys = list(self.model_graph[input_node_id].outputs.keys())
323
- for output_key in output_keys:
324
- new_output_key = f'{input_node_id}-{input_node.name}'
325
- if output_key == new_output_key:
326
- continue
327
- self.model_graph[input_node_id].outputs[new_output_key] = self.model_graph[input_node_id].outputs[output_key]
328
- del self.model_graph[input_node_id].outputs[output_key]
329
- for connection in self.model_graph[input_node_id].outputs[new_output_key].connections:
330
- for connection_input in self.model_graph[connection.node].inputs[connection.input].connections:
331
- if connection_input.output == output_key:
332
- connection_input.output = new_output_key
333
-
334
- if input_node_id is None:
335
- raise Exception(f"Couldn't find input node by origin name {origin_name}")
238
+ input_node_id = self._handle_input_node_with_index(input_node)
336
239
  elif input_node.type.value.startswith('Prediction'):
337
- input_node_id = self._find_node_by_origin_name(input_node.name).id
240
+ node_by_origin_name = self._find_node_by_origin_name(input_node.name)
241
+ assert node_by_origin_name is not None, \
242
+ f"Prediction node with name {input_node.name} not found in model graph"
243
+ input_node_id = node_by_origin_name.id
338
244
  else:
339
245
  input_node_id = self._find_layer_node_id(input_node.name)
340
246
 
@@ -350,13 +256,6 @@ class LeapGraphEditor:
350
256
  loss_node_ids.append(node_id)
351
257
  return loss_node_ids
352
258
 
353
- # def _get_dataset_node(self) -> NodeResponse:
354
- # for node_response in self.model_graph.values():
355
- # if 'type' in node_response.data and node_response.data['type'] == 'dataset':
356
- # return node_response
357
- #
358
- # raise Exception("Didn't find dataset node")
359
-
360
259
  @staticmethod
361
260
  def _convert_dataclass_to_json_dict(_dataclass):
362
261
  if isinstance(_dataclass, Enum):
@@ -372,20 +271,3 @@ class LeapGraphEditor:
372
271
  for element in _dataclass
373
272
  ]
374
273
  return _dataclass
375
-
376
- # @staticmethod
377
- # def _add_setup_to_metadata(dataset_version_metadata: Dict[str, Any],
378
- # dataset_parse_result: DatasetIntegParseResult):
379
- # setup_json = LeapGraphEditor._convert_dataclass_to_json_dict(dataset_parse_result.setup)
380
- #
381
- # dataset_version_metadata['setup'] = setup_json
382
-
383
- # def _add_arg_names_to_visualizers(self, dataset_parse_result: DatasetIntegParseResult):
384
- # visualizer_instance_by_name: Dict[str, VisualizerInstance] = {
385
- # visualizer_instance.name: visualizer_instance
386
- # for visualizer_instance in dataset_parse_result.setup.visualizers
387
- # }
388
- #
389
- # for _, node_response in self.model_graph.items():
390
- # if node_response.data['type'] == 'Visualizer':
391
- # node_response.data['arg_names'] = visualizer_instance_by_name[node_response.data['selected']].arg_names
@@ -5,10 +5,10 @@ import tarfile
5
5
  import tempfile
6
6
  from importlib.util import find_spec
7
7
  from pathlib import Path
8
- from typing import Callable, Optional, List, Dict, Tuple, Type
8
+
9
9
 
10
10
  import tensorflow as tf # type: ignore
11
- from code_loader.contract.mapping import NodeConnection, leap_output
11
+ from code_loader.contract.mapping import NodeConnection # type: ignore
12
12
  from keras import Model # type: ignore
13
13
  from keras_data_format_converter import convert_channels_first_to_last # type: ignore
14
14
  from leap_model_rebuilder import rebuild_model # type: ignore
@@ -21,7 +21,9 @@ from tensorflow.keras.models import load_model # type: ignore
21
21
  from leap_model_parser.contract.graph import Node, InputInfo
22
22
  from leap_model_parser.contract.importmodelresponse import ImportModelTypeEnum
23
23
  from leap_model_parser.keras_json_model_import import KerasJsonModelImport
24
- from leap_model_parser.leap_graph_editor import LeapGraphEditor
24
+ from leap_model_parser.leap_graph_editor import LeapGraphEditor # type: ignore
25
+
26
+ from typing import Callable, Optional, List, Dict, Tuple, Type
25
27
 
26
28
  onnx_imported = False
27
29
  package_name = 'onnx'
@@ -33,7 +35,7 @@ if spec is not None:
33
35
 
34
36
  class ModelParser:
35
37
  def __init__(self, should_transform_inputs_and_outputs=False,
36
- custom_layers: Optional[Dict[str, Type[tf.keras.layers.Layer]]] = None,
38
+ custom_layers=None,
37
39
  mapping_connections: Optional[List[NodeConnection]] = None):
38
40
  self._should_transform_inputs_and_outputs = should_transform_inputs_and_outputs
39
41
  self.custom_layers = custom_layers
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: leap-model-parser
3
- Version: 0.1.185.dev11
3
+ Version: 0.1.187
4
4
  Summary:
5
5
  Home-page: https://github.com/tensorleap/leap-model-parser
6
6
  License: MIT
@@ -12,7 +12,7 @@ Classifier: Programming Language :: Python :: 3
12
12
  Classifier: Programming Language :: Python :: 3.8
13
13
  Classifier: Programming Language :: Python :: 3.9
14
14
  Classifier: Programming Language :: Python :: 3.10
15
- Requires-Dist: code-loader (==1.0.87.dev7)
15
+ Requires-Dist: code-loader (==1.0.89)
16
16
  Requires-Dist: keras-data-format-converter (==0.1.22)
17
17
  Requires-Dist: leap-model-rebuilder (==0.1.7)
18
18
  Requires-Dist: numpy (>=1.22.3,<2.0.0)
@@ -6,8 +6,8 @@ leap_model_parser/contract/importmodelresponse.py,sha256=GlvnKS8xrebU2Sj0dxqtEhA
6
6
  leap_model_parser/contract/nodedata.py,sha256=1_ML0nzp3QUZ0_9mGSLhfO4_hqjYMwi0DWLwymUnWEs,43326
7
7
  leap_model_parser/contract/ui_components.json,sha256=0lsxwOLElW1E-imCcdh3zKPWgzFuQ_bApG6aHvYfTvo,410591
8
8
  leap_model_parser/keras_json_model_import.py,sha256=x7HOH6iaASfzJgwMRHgF5SQS-iFOF5j9yCG0mDC9HEA,16794
9
- leap_model_parser/leap_graph_editor.py,sha256=wbvM9zDo-nLn-MPRDLJM9C7EKtE43D1KqciwsjvjDc0,17888
10
- leap_model_parser/model_parser.py,sha256=1EeSwlaznRRMgLeltAcDnlRWZCMpWeXySglYQEYeiRI,6618
9
+ leap_model_parser/leap_graph_editor.py,sha256=T9IIABlJ9NwAEUGRFlsrsD-c3yeFfUazbbvE6mLXnMA,13022
10
+ leap_model_parser/model_parser.py,sha256=kodF6aCPXP5FzZR9To2txqu6YdwklmhdJbyQKO_hghM,6587
11
11
  leap_model_parser/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
12
  leap_model_parser/utils/layerpedia/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
13
  leap_model_parser/utils/layerpedia/layerpedia.py,sha256=1syubfXBTB630TVkgcQ-Ge7Qe9Zbr6EtZRreuqCJnQ8,9292
@@ -18,8 +18,8 @@ leap_model_parser/utils/uicomponents/generatenodedata.py,sha256=LRaPlO5jJ9pUtkvL
18
18
  leap_model_parser/utils/uicomponents/tensorflowinscpection.py,sha256=ym613z9iQKPDBpr0RYD35bTABdm1L-Ez86G47BYT7qw,6775
19
19
  leap_model_parser/utils/uicomponents/ui_components.json,sha256=0lsxwOLElW1E-imCcdh3zKPWgzFuQ_bApG6aHvYfTvo,410591
20
20
  leap_model_parser/utils/uicomponents/ui_components_config.yaml,sha256=cRH8T-c3TAL0nfefRvt9pFsjbTWNEg38NRyHR7RpJsk,19534
21
- leap_model_parser-0.1.185.dev11.dist-info/LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
22
- leap_model_parser-0.1.185.dev11.dist-info/METADATA,sha256=OO79gPOX78m2BeUv5ulVMARwxmgL918c_Nvfu7qmxd8,1114
23
- leap_model_parser-0.1.185.dev11.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
24
- leap_model_parser-0.1.185.dev11.dist-info/entry_points.txt,sha256=ZvV6EuQt1uAqwapNg5Lo2qjJM9ZG5g2wfzZoLh_Ztyk,77
25
- leap_model_parser-0.1.185.dev11.dist-info/RECORD,,
21
+ leap_model_parser-0.1.187.dist-info/LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
22
+ leap_model_parser-0.1.187.dist-info/METADATA,sha256=dTub6iKB7pQaX8UJN1QOz6AgY7cIMVnHNemlYrBax_8,1103
23
+ leap_model_parser-0.1.187.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
24
+ leap_model_parser-0.1.187.dist-info/entry_points.txt,sha256=ZvV6EuQt1uAqwapNg5Lo2qjJM9ZG5g2wfzZoLh_Ztyk,77
25
+ leap_model_parser-0.1.187.dist-info/RECORD,,