Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / front / tf / tensorflow_custom_operations_config_update.py
1 """
2  Copyright (c) 2019 Intel Corporation
3
4  Licensed under the Apache License, Version 2.0 (the "License");
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7
8       http://www.apache.org/licenses/LICENSE-2.0
9
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15 """
16 import json
17
18 from mo.front.common.replacement import FrontReplacementPattern
19 from mo.graph.graph import Graph
20 from mo.utils.custom_replacement_config import parse_custom_replacement_config_file
21 from mo.utils.error import Error
22 from mo.utils.utils import refer_to_faq_msg
23
24
25 class TensorflowCustomOperationsConfigUpdate(FrontReplacementPattern):
26     enabled = True
27     graph_condition = [lambda graph: graph.graph['cmd_params'].tensorflow_custom_operations_config_update is not None]
28
29     def run_before(self):
30         return []
31
32     def run_after(self):
33         from extensions.front.freeze_placeholder_value import FreezePlaceholderValue
34         return [FreezePlaceholderValue]
35
36     @staticmethod
37     def save_custom_replacement_config_file(descriptions: list, file_name: str):
38         """
39         Save custom layer(s) description(s) to the file.
40         :param file_name: file to save description information to.
41         :param descriptions: list with instances of the CustomLayerDescriptor classes.
42         :return: True if operation is successful.
43         """
44         try:
45             json.dump([replacement_desc.get_config_file_representation() for replacement_desc in descriptions],
46                       open(file_name, "w"), indent=4, sort_keys=True)
47         except Exception as ex:
48             raise Error("failed to update configuration file {}: {}".format(file_name, str(ex)))
49
50     def find_and_replace_pattern(self, graph: Graph):
51         argv = graph.graph['cmd_params']
52         file_name = argv.tensorflow_custom_operations_config_update
53
54         data = parse_custom_replacement_config_file(file_name)
55         if data is None:
56             raise Error("Cannot update the file '{}' because it is broken. ".format(file_name) + refer_to_faq_msg(73))
57
58         for replacement_desc in data:
59             replacement_desc.update_custom_replacement_attributes(graph)
60
61         self.save_custom_replacement_config_file(data, file_name)