infer.py 7.5 KB
Newer Older
1
"""Inferer for DeepSpeech2 model."""
2 3 4
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
X
Xinghai Sun 已提交
5

6 7
import argparse
import gzip
8
import distutils.util
9
import multiprocessing
10 11
import paddle.v2 as paddle
from data_utils.data import DataGenerator
X
Xinghai Sun 已提交
12
from model import deep_speech2
Y
Yibing Liu 已提交
13
from decoder import *
Y
Yibing Liu 已提交
14
from lm.lm_scorer import LmScorer
15
from error_rate import wer
16
import utils
17

18
parser = argparse.ArgumentParser(description=__doc__)
19
parser.add_argument(
X
Xinghai Sun 已提交
20
    "--num_samples",
Y
Yibing Liu 已提交
21
    default=10,
X
Xinghai Sun 已提交
22
    type=int,
23
    help="Number of samples for inference. (default: %(default)s)")
24
parser.add_argument(
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
    "--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)")
44 45
parser.add_argument(
    "--num_threads_data",
46
    default=multiprocessing.cpu_count(),
47 48
    type=int,
    help="Number of cpu threads for preprocessing data. (default: %(default)s)")
Y
Yibing Liu 已提交
49 50 51 52 53
parser.add_argument(
    "--num_processes_beam_search",
    default=multiprocessing.cpu_count(),
    type=int,
    help="Number of cpu processes for beam search. (default: %(default)s)")
54 55 56 57 58 59
parser.add_argument(
    "--specgram_type",
    default='linear',
    type=str,
    help="Feature type of audio data: 'linear' (power spectrum)"
    " or 'mfcc'. (default: %(default)s)")
60
parser.add_argument(
61 62
    "--mean_std_filepath",
    default='mean_std.npz',
63 64
    type=str,
    help="Manifest path for normalizer. (default: %(default)s)")
65
parser.add_argument(
66
    "--decode_manifest_path",
Y
Yibing Liu 已提交
67
    default='datasets/manifest.test',
68 69
    type=str,
    help="Manifest path for decoding. (default: %(default)s)")
70
parser.add_argument(
71
    "--model_filepath",
Y
Yibing Liu 已提交
72
    default='checkpoints/params.latest.tar.gz',
73 74
    type=str,
    help="Model filepath. (default: %(default)s)")
75 76
parser.add_argument(
    "--vocab_filepath",
77
    default='datasets/vocab/eng_vocab.txt',
78 79
    type=str,
    help="Vocabulary filepath. (default: %(default)s)")
Y
Yibing Liu 已提交
80 81
parser.add_argument(
    "--decode_method",
Y
Yibing Liu 已提交
82
    default='beam_search',
Y
Yibing Liu 已提交
83
    type=str,
Y
Yibing Liu 已提交
84 85
    help="Method for ctc decoding: best_path or beam_search. (default: %(default)s)"
)
Y
Yibing Liu 已提交
86 87
parser.add_argument(
    "--beam_size",
88
    default=500,
Y
Yibing Liu 已提交
89 90 91
    type=int,
    help="Width for beam search decoding. (default: %(default)d)")
parser.add_argument(
Y
Yibing Liu 已提交
92 93
    "--num_results_per_sample",
    default=1,
Y
Yibing Liu 已提交
94
    type=int,
Y
Yibing Liu 已提交
95 96 97
    help="Number of output per sample in beam search. (default: %(default)d)")
parser.add_argument(
    "--language_model_path",
Y
Yibing Liu 已提交
98
    default="lm/data/common_crawl_00.prune01111.trie.klm",
Y
Yibing Liu 已提交
99
    type=str,
Y
Yibing Liu 已提交
100
    help="Path for language model. (default: %(default)s)")
Y
Yibing Liu 已提交
101 102
parser.add_argument(
    "--alpha",
103
    default=0.26,
Y
Yibing Liu 已提交
104 105 106 107
    type=float,
    help="Parameter associated with language model. (default: %(default)f)")
parser.add_argument(
    "--beta",
108
    default=0.1,
Y
Yibing Liu 已提交
109 110
    type=float,
    help="Parameter associated with word count. (default: %(default)f)")
111 112 113 114 115 116
parser.add_argument(
    "--cutoff_prob",
    default=0.99,
    type=float,
    help="The cutoff probability of pruning"
    "in beam search. (default: %(default)f)")
117 118 119
args = parser.parse_args()


120
def infer():
Y
Yibing Liu 已提交
121
    """Inference for DeepSpeech2."""
122 123
    # initialize data generator
    data_generator = DataGenerator(
124
        vocab_filepath=args.vocab_filepath,
125
        mean_std_filepath=args.mean_std_filepath,
126
        augmentation_config='{}',
127
        specgram_type=args.specgram_type,
128
        num_threads=args.num_threads_data)
129

130
    # create network config
131 132 133
    # paddle.data_type.dense_array is used for variable batch input.
    # The size 161 * 161 is only an placeholder value and the real shape
    # of input batch data will be induced during training.
134
    audio_data = paddle.layer.data(
135
        name="audio_spectrogram", type=paddle.data_type.dense_array(161 * 161))
136 137
    text_data = paddle.layer.data(
        name="transcript_text",
138
        type=paddle.data_type.integer_value_sequence(data_generator.vocab_size))
139
    output_probs = deep_speech2(
140 141
        audio_data=audio_data,
        text_data=text_data,
142
        dict_size=data_generator.vocab_size,
143 144
        num_conv_layers=args.num_conv_layers,
        num_rnn_layers=args.num_rnn_layers,
145 146
        rnn_size=args.rnn_layer_size,
        is_inference=True)
147 148 149

    # load parameters
    parameters = paddle.parameters.Parameters.from_tar(
150
        gzip.open(args.model_filepath))
151 152

    # prepare infer data
153
    batch_reader = data_generator.batch_reader_creator(
154 155
        manifest_path=args.decode_manifest_path,
        batch_size=args.num_samples,
Y
Yibing Liu 已提交
156
        min_batch_size=1,
157
        sortagrad=False,
158
        shuffle_method=None)
159
    infer_data = batch_reader().next()
160

161 162 163
    # run inference
    infer_results = paddle.infer(
        output_layer=output_probs, parameters=parameters, input=infer_data)
164
    num_steps = len(infer_results) // len(infer_data)
165 166
    probs_split = [
        infer_results[i * num_steps:(i + 1) * num_steps]
167
        for i in xrange(len(infer_data))
168
    ]
169

Y
Yibing Liu 已提交
170 171 172 173 174 175 176
    # targe transcription
    target_transcription = [
        ''.join(
            [data_generator.vocab_list[index] for index in infer_data[i][1]])
        for i, probs in enumerate(probs_split)
    ]

Y
Yibing Liu 已提交
177 178
    ## decode and print
    # best path decode
179
    wer_sum, wer_counter = 0, 0
Y
Yibing Liu 已提交
180 181
    if args.decode_method == "best_path":
        for i, probs in enumerate(probs_split):
Y
Yibing Liu 已提交
182
            best_path_transcription = ctc_best_path_decoder(
Y
Yibing Liu 已提交
183
                probs_seq=probs, vocabulary=data_generator.vocab_list)
Y
Yibing Liu 已提交
184
            print("\nTarget Transcription: %s\nOutput Transcription: %s" %
Y
Yibing Liu 已提交
185 186
                  (target_transcription[i], best_path_transcription))
            wer_cur = wer(target_transcription[i], best_path_transcription)
187 188 189 190
            wer_sum += wer_cur
            wer_counter += 1
            print("cur wer = %f, average wer = %f" %
                  (wer_cur, wer_sum / wer_counter))
Y
Yibing Liu 已提交
191 192
    # beam search decode
    elif args.decode_method == "beam_search":
Y
Yibing Liu 已提交
193 194
        ext_scorer = LmScorer(args.alpha, args.beta, args.language_model_path)
        beam_search_batch_results = ctc_beam_search_decoder_batch(
195
            probs_split=probs_split,
196
            vocabulary=data_generator.vocab_list,
197
            beam_size=args.beam_size,
Y
Yibing Liu 已提交
198
            blank_id=len(data_generator.vocab_list),
Y
Yibing Liu 已提交
199
            num_processes=args.num_processes_beam_search,
200 201
            cutoff_prob=args.cutoff_prob,
            ext_scoring_func=ext_scorer, )
Y
Yibing Liu 已提交
202 203
        for i, beam_search_result in enumerate(beam_search_batch_results):
            print("\nTarget Transcription:\t%s" % target_transcription[i])
204
            for index in xrange(args.num_results_per_sample):
Y
Yibing Liu 已提交
205
                result = beam_search_result[index]
Y
Yibing Liu 已提交
206
                #output: index, log prob, beam result
Y
Yibing Liu 已提交
207
                print("Beam %d: %f \t%s" % (index, result[0], result[1]))
Y
Yibing Liu 已提交
208
            wer_cur = wer(target_transcription[i], beam_search_result[0][1])
209 210 211 212
            wer_sum += wer_cur
            wer_counter += 1
            print("cur wer = %f , average wer = %f" %
                  (wer_cur, wer_sum / wer_counter))
Y
Yibing Liu 已提交
213
    else:
Y
Yibing Liu 已提交
214 215
        raise ValueError("Decoding method [%s] is not supported." %
                         decode_method)
216 217 218


def main():
219
    utils.print_arguments(args)
220
    paddle.init(use_gpu=args.use_gpu, trainer_count=1)
221
    infer()
222 223 224 225


if __name__ == '__main__':
    main()