2 Copyright (c) 2018-2019 Intel Corporation
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
8 http://www.apache.org/licenses/LICENSE-2.0
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.
23 from mo.back.replacement import BackReplacementPattern
24 from mo.middle.replacement import MiddleReplacementPattern
25 from mo.ops.op import Op
26 from mo.utils.class_registration import _check_unique_ids, update_registration, get_enabled_and_disabled_transforms
29 def import_by_path(path: str, middle_names: list = ()):
30 for module_loader, name, ispkg in pkgutil.iter_modules([path]):
31 importlib.import_module('{}.{}'.format('.'.join(middle_names), name))
35 EXT_DIR_NAME = 'extensions'
36 return os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, EXT_DIR_NAME))
39 def load_dir(framework: str, path: str, get_front_classes: callable):
41 Assuming the following sub-directory structure for path:
55 This function loads modules in the following order:
57 2. front/<other_files>.py
58 3. front/<framework>/<other_files>.py
59 4. middle/<other_files>.py
60 5. back/<other_files>.py
62 Handlers loaded later override earlier registered handlers for an op.
63 1, 2, 3 can concur for the same op, but 4 registers a transformation pass
64 and it shouldn't conflict with any stuff loaded by 1, 2 or 3.
65 It doesn't load files from front/<other_directories>
67 log.info("Importing extensions from: {}".format(path))
68 root_dir, ext = os.path.split(path)
69 sys.path.insert(0, root_dir)
71 enabled_transforms, disabled_transforms = get_enabled_and_disabled_transforms()
73 front_classes = get_front_classes()
76 ('front', ): front_classes,
77 ('front', framework): front_classes,
78 ('middle', ): [MiddleReplacementPattern],
79 ('back', ): [BackReplacementPattern]}
82 internal_dirs[('front', framework, 'extractors')] = front_classes
84 for p in internal_dirs.keys():
85 import_by_path(os.path.join(path, *p), [ext, *p])
86 update_registration(internal_dirs[p], enabled_transforms, disabled_transforms)
87 sys.path.remove(root_dir)
90 def load_dirs(framework: str, dirs: list, get_front_classes: callable):
94 mo_inner_extensions = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, 'mo'))
95 dirs.insert(0, mo_inner_extensions)
96 dirs = [os.path.abspath(e) for e in dirs]
97 if default_path() not in dirs:
98 dirs.insert(0, default_path())
100 load_dir(framework, path, get_front_classes)