Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / mo / utils / convert.py
1 #!/usr/bin/env python3
2 """
3  Copyright (c) 2018-2019 Intel Corporation
4
5  Licensed under the Apache License, Version 2.0 (the "License");
6  you may not use this file except in compliance with the License.
7  You may obtain a copy of the License at
8
9       http://www.apache.org/licenses/LICENSE-2.0
10
11  Unless required by applicable law or agreed to in writing, software
12  distributed under the License is distributed on an "AS IS" BASIS,
13  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  See the License for the specific language governing permissions and
15  limitations under the License.
16 """
17 import argparse
18 import os
19 import sys
20
21 import tensorflow as tf
22
23 sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
24 from mo.front.tf.loader import load_tf_graph_def
25
26 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
27
28
29 def argparser():
30     parser = argparse.ArgumentParser()
31     parser.add_argument("--to_pbtxt", dest='pb', type=str, help="Path to TensorFlow binary model")
32     parser.add_argument('--to_pb', dest='pbtxt', type=str, help="Path to TensorFlow text model")
33     return parser.parse_args()
34
35
36 def convert(filename: str, is_text: bool):
37     if not os.path.isfile(filename):
38         raise FileNotFoundError("File doesn't exist: {}".format(filename))
39     new_ext = ".pbtxt" if is_text else ".pb"
40     head, tail = os.path.split(os.path.abspath(filename))
41     print("Convert: {} \n     to: {}".format(filename, os.path.join(head, tail + new_ext)))
42     graph_def, _ = load_tf_graph_def(graph_file_name=filename, is_binary=is_text)
43     tf.import_graph_def(graph_def, name='')
44     tf.train.write_graph(graph_def, head, tail + new_ext, as_text=is_text)
45
46
47 if __name__ == '__main__':
48     argv = argparser()
49     if argv.pb is None and argv.pbtxt is None:
50         print("Please provide model to convert --to_pb or --to_pbtxt")
51         sys.exit(1)
52     if argv.pb is not None:
53         convert(argv.pb, True)
54     if argv.pbtxt is not None:
55         convert(argv.pbtxt, False)