Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / mo / front / kaldi / utils.py
1 """
2  Copyright (c) 2018-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 io
17 import numpy as np
18 import os
19 import logging as log
20
21 from mo.front.kaldi.loader.utils import read_placeholder, read_binary_integer32_token, read_blob, read_token_value, find_next_tag
22 from mo.utils.error import Error
23
24
25 def read_binary_matrix(file_desc: io.BufferedReader, read_token: bool = True):
26     if read_token:
27         read_placeholder(file_desc)
28     rows_number = read_binary_integer32_token(file_desc)
29     cols_number = read_binary_integer32_token(file_desc)
30     # to compare: ((float *)a->buffer())[10]
31     return read_blob(file_desc, rows_number * cols_number), (rows_number, cols_number)
32
33
34 def read_binary_vector(file_desc: io.BufferedReader, read_token: bool = True, dtype=np.float32):
35     if read_token:
36         read_placeholder(file_desc)
37     elements_number = read_binary_integer32_token(file_desc)
38     return read_blob(file_desc, elements_number, dtype)
39
40
41 def read_learning_info(pb: io.BufferedReader):
42     while True:
43         read_placeholder(pb, 1)
44         first_char = pb.read(1)
45         pb.seek(-2, os.SEEK_CUR)
46         position = pb.tell()
47         if first_char == b'L':
48             cur_pos = pb.tell()
49             token = find_next_tag(pb)
50             pb.seek(cur_pos)
51             if token in ['<LearnRateCoef>', '<LearningRate>']:
52                 token = bytes(token, 'ascii')
53             else:
54                 log.debug('Unexpected tag: {}'.format(token))
55                 break
56         elif first_char == b'B':
57             token = b'<BiasLearnRateCoef>'
58         elif first_char == b'M':
59             token = b'<MaxNorm>'
60         elif first_char == b'!':  # token = b'<EndOfComponent>'
61             break
62         else:
63             break
64         try:
65             read_token_value(pb, token)
66         except Error:
67             pb.seek(position)
68             break
69