infer.py 7.7 KB
Newer Older
X
Xinghai Sun 已提交
1 2 3 4
"""
   Inference for a simplifed version of Baidu DeepSpeech2 model.
"""

5
import paddle.v2 as paddle
6
import distutils.util
7 8
import argparse
import gzip
9
from audio_data_utils import DataGenerator
X
Xinghai Sun 已提交
10
from model import deep_speech2
Y
Yibing Liu 已提交
11
from decoder import *
12
import kenlm
13
from error_rate import wer
14 15

parser = argparse.ArgumentParser(
X
Xinghai Sun 已提交
16
    description='Simplified version of DeepSpeech2 inference.')
17
parser.add_argument(
X
Xinghai Sun 已提交
18 19 20
    "--num_samples",
    default=10,
    type=int,
21
    help="Number of samples for inference. (default: %(default)s)")
22
parser.add_argument(
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
    "--num_conv_layers",
    default=2,
    type=int,
    help="Convolution layer number. (default: %(default)s)")
parser.add_argument(
    "--num_rnn_layers",
    default=3,
    type=int,
    help="RNN layer number. (default: %(default)s)")
parser.add_argument(
    "--rnn_layer_size",
    default=512,
    type=int,
    help="RNN layer cell number. (default: %(default)s)")
parser.add_argument(
    "--use_gpu",
    default=True,
    type=distutils.util.strtobool,
    help="Use gpu or not. (default: %(default)s)")
42
parser.add_argument(
43
    "--normalizer_manifest_path",
44
    default='data/manifest.libri.train-clean-100',
45 46
    type=str,
    help="Manifest path for normalizer. (default: %(default)s)")
47
parser.add_argument(
48
    "--decode_manifest_path",
49
    default='data/manifest.libri.test-clean',
50 51
    type=str,
    help="Manifest path for decoding. (default: %(default)s)")
52
parser.add_argument(
53 54 55 56
    "--model_filepath",
    default='./params.tar.gz',
    type=str,
    help="Model filepath. (default: %(default)s)")
57 58 59 60 61
parser.add_argument(
    "--vocab_filepath",
    default='data/eng_vocab.txt',
    type=str,
    help="Vocabulary filepath. (default: %(default)s)")
Y
Yibing Liu 已提交
62 63
parser.add_argument(
    "--decode_method",
64
    default='beam_search_nproc',
Y
Yibing Liu 已提交
65
    type=str,
66
    help="Method for ctc decoding, best_path, beam_search or beam_search_nproc. (default: %(default)s)"
Y
Yibing Liu 已提交
67 68 69 70 71 72 73
)
parser.add_argument(
    "--beam_size",
    default=50,
    type=int,
    help="Width for beam search decoding. (default: %(default)d)")
parser.add_argument(
Y
Yibing Liu 已提交
74 75
    "--num_results_per_sample",
    default=1,
Y
Yibing Liu 已提交
76
    type=int,
Y
Yibing Liu 已提交
77 78 79 80 81
    help="Number of output per sample in beam search. (default: %(default)d)")
parser.add_argument(
    "--language_model_path",
    default="./data/1Billion.klm",
    type=str,
Y
Yibing Liu 已提交
82
    help="Path for language model. (default: %(default)s)")
Y
Yibing Liu 已提交
83 84 85 86 87 88 89 90 91 92
parser.add_argument(
    "--alpha",
    default=0.0,
    type=float,
    help="Parameter associated with language model. (default: %(default)f)")
parser.add_argument(
    "--beta",
    default=0.0,
    type=float,
    help="Parameter associated with word count. (default: %(default)f)")
93 94 95
args = parser.parse_args()


96
def infer():
X
Xinghai Sun 已提交
97
    """
Y
Yibing Liu 已提交
98
    Inference for DeepSpeech2.
X
Xinghai Sun 已提交
99
    """
100 101
    # initialize data generator
    data_generator = DataGenerator(
102
        vocab_filepath=args.vocab_filepath,
103 104 105 106 107 108
        normalizer_manifest_path=args.normalizer_manifest_path,
        normalizer_num_samples=200,
        max_duration=20.0,
        min_duration=0.0,
        stride_ms=10,
        window_ms=20)
109

110
    # create network config
111 112
    dict_size = data_generator.vocabulary_size()
    vocab_list = data_generator.vocabulary_list()
113 114 115
    audio_data = paddle.layer.data(
        name="audio_spectrogram",
        height=161,
116 117
        width=2000,
        type=paddle.data_type.dense_vector(322000))
118 119 120
    text_data = paddle.layer.data(
        name="transcript_text",
        type=paddle.data_type.integer_value_sequence(dict_size))
121
    output_probs = deep_speech2(
122 123 124 125 126
        audio_data=audio_data,
        text_data=text_data,
        dict_size=dict_size,
        num_conv_layers=args.num_conv_layers,
        num_rnn_layers=args.num_rnn_layers,
127 128
        rnn_size=args.rnn_layer_size,
        is_inference=True)
129 130 131

    # load parameters
    parameters = paddle.parameters.Parameters.from_tar(
132
        gzip.open(args.model_filepath))
133 134

    # prepare infer data
135 136 137 138 139 140 141 142
    feeding = data_generator.data_name_feeding()
    test_batch_reader = data_generator.batch_reader_creator(
        manifest_path=args.decode_manifest_path,
        batch_size=args.num_samples,
        padding_to=2000,
        flatten=True,
        sort_by_duration=False,
        shuffle=False)
143 144
    infer_data = test_batch_reader().next()

145 146 147 148 149 150 151
    # run inference
    infer_results = paddle.infer(
        output_layer=output_probs, parameters=parameters, input=infer_data)
    num_steps = len(infer_results) / len(infer_data)
    probs_split = [
        infer_results[i * num_steps:(i + 1) * num_steps]
        for i in xrange(0, len(infer_data))
152
    ]
153

Y
Yibing Liu 已提交
154 155
    ## decode and print
    # best path decode
156
    wer_sum, wer_counter = 0, 0
Y
Yibing Liu 已提交
157 158 159 160 161 162 163 164
    if args.decode_method == "best_path":
        for i, probs in enumerate(probs_split):
            target_transcription = ''.join(
                [vocab_list[index] for index in infer_data[i][1]])
            best_path_transcription = ctc_best_path_decode(
                probs_seq=probs, vocabulary=vocab_list)
            print("\nTarget Transcription: %s\nOutput Transcription: %s" %
                  (target_transcription, best_path_transcription))
165 166 167 168 169
            wer_cur = wer(target_transcription, best_path_transcription)
            wer_sum += wer_cur
            wer_counter += 1
            print("cur wer = %f, average wer = %f" %
                  (wer_cur, wer_sum / wer_counter))
Y
Yibing Liu 已提交
170 171
    # beam search decode
    elif args.decode_method == "beam_search":
172
        ext_scorer = Scorer(args.alpha, args.beta, args.language_model_path)
Y
Yibing Liu 已提交
173 174 175 176 177 178 179
        for i, probs in enumerate(probs_split):
            target_transcription = ''.join(
                [vocab_list[index] for index in infer_data[i][1]])
            beam_search_result = ctc_beam_search_decoder(
                probs_seq=probs,
                vocabulary=vocab_list,
                beam_size=args.beam_size,
180
                ext_scoring_func=ext_scorer,
Y
Yibing Liu 已提交
181 182
                blank_id=len(vocab_list))
            print("\nTarget Transcription:\t%s" % target_transcription)
183 184 185 186 187 188 189 190 191 192

            for index in range(args.num_results_per_sample):
                result = beam_search_result[index]
                #output: index, log prob, beam result
                print("Beam %d: %f \t%s" % (index, result[0], result[1]))
            wer_cur = wer(target_transcription, beam_search_result[0][1])
            wer_sum += wer_cur
            wer_counter += 1
            print("cur wer = %f , average wer = %f" %
                  (wer_cur, wer_sum / wer_counter))
Y
Yibing Liu 已提交
193
    # beam search using multiple processes
194 195 196 197 198 199
    elif args.decode_method == "beam_search_nproc":
        ext_scorer = Scorer(args.alpha, args.beta, args.language_model_path)
        beam_search_nproc_results = ctc_beam_search_decoder_nproc(
            probs_split=probs_split,
            vocabulary=vocab_list,
            beam_size=args.beam_size,
200 201 202
            ext_scoring_func=ext_scorer,
            blank_id=len(vocab_list),
            num_processes=1)
203 204 205 206 207
        for i, beam_search_result in enumerate(beam_search_nproc_results):
            target_transcription = ''.join(
                [vocab_list[index] for index in infer_data[i][1]])
            print("\nTarget Transcription:\t%s" % target_transcription)

Y
Yibing Liu 已提交
208 209
            for index in range(args.num_results_per_sample):
                result = beam_search_result[index]
Y
Yibing Liu 已提交
210
                #output: index, log prob, beam result
Y
Yibing Liu 已提交
211
                print("Beam %d: %f \t%s" % (index, result[0], result[1]))
212 213 214 215 216
            wer_cur = wer(target_transcription, beam_search_result[0][1])
            wer_sum += wer_cur
            wer_counter += 1
            print("cur wer = %f , average wer = %f" %
                  (wer_cur, wer_sum / wer_counter))
Y
Yibing Liu 已提交
217 218
    else:
        raise ValueError("Decoding method [%s] is not supported." % method)
219 220 221 222


def main():
    paddle.init(use_gpu=args.use_gpu, trainer_count=1)
223
    infer()
224 225 226 227


if __name__ == '__main__':
    main()