Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / mo / front / common / custom_replacement_registry.py
1 """
2  Copyright (c) 2017-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
17 import logging as log
18 import os
19
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 CustomReplacementRegistry(object):
26     """
27     Registry that contains registered custom calls descriptors.
28     """
29
30     class __CustomReplacementRegistry:
31         def __init__(self):
32             self.registry = {}
33
34         def __str__(self):
35             return repr(self) + str(self.registry)
36
37     def __init__(self):
38         if not CustomReplacementRegistry.instance:
39             CustomReplacementRegistry.instance = CustomReplacementRegistry.__CustomReplacementRegistry()
40         else:
41             pass
42             # CustomCallRegistry.instance.val = arg
43
44     def __getattr__(self, name):
45         return getattr(self.instance, name)
46
47     instance = None
48
49     def add_custom_replacement_description_from_config(self, file_name: str):
50         if not os.path.exists(file_name):
51             raise Error("Custom replacement configuration file '{}' doesn't exist. ".format(file_name) +
52                         refer_to_faq_msg(46))
53
54         descriptions = parse_custom_replacement_config_file(file_name)
55         for desc in descriptions:
56             self.registry.setdefault(desc.id, list()).append(desc)
57             log.info("Registered custom replacement with id '{}'".format(desc.id))
58
59     def get_custom_replacement_description(self, replacement_id: str):
60         if replacement_id in self.registry:
61             return self.registry[replacement_id]
62         else:
63             log.warning("Configuration file for custom replacement with id '{}' doesn't exist".format(replacement_id))
64             return None
65
66     def get_all_replacements_descriptions(self):
67         result = list()
68         for l in self.registry.values():
69             result.extend(l)
70         return result