infer.py 4.9 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
import argparse
7 8 9
import distutils.util
import paddle.v2 as paddle
from data_utils.data import DataGenerator
10
from model import DeepSpeech2Model
Y
yangyaming 已提交
11
from error_rate import wer, cer
12

13 14 15 16 17 18 19 20 21 22 23 24

def add_arg(argname, type, default, help, **kwargs):
    type = distutils.util.strtobool if type == bool else type
    parser.add_argument(
        "--" + argname,
        default=default,
        type=type,
        help=help + ' Default: %(default)s.',
        **kwargs)


# yapf: disable
25
parser = argparse.ArgumentParser(description=__doc__)
26 27 28
add_arg('num_samples',      int,    10,     "# of samples to infer.")
add_arg('trainer_count',    int,    8,      "# of Trainers (CPUs or GPUs).")
add_arg('beam_size',        int,    500,    "Beam search width.")
29
add_arg('parallels_bsearch',int,    12,     "# of CPUs for beam search.")
30 31 32
add_arg('num_conv_layers',  int,    2,      "# of convolution layers.")
add_arg('num_rnn_layers',   int,    3,      "# of recurrent layers.")
add_arg('rnn_layer_size',   int,    2048,   "# of recurrent cells per layer.")
33 34 35
add_arg('alpha',            float,  0.36,   "Coef of LM for beam search.")
add_arg('beta',             float,  0.25,   "Coef of WC for beam search.")
add_arg('cutoff_prob',      float,  0.99,   "Cutoff probability for pruning.")
36
add_arg('use_gru',          bool,   False,  "Use GRUs instead of Simple RNNs.")
37
add_arg('use_gpu',          bool,   True,   "Use GPU or not.")
38 39 40 41 42 43 44 45 46 47 48
add_arg('share_rnn_weights',bool,   True,   "Share input-hidden weights across "
                                            "bi-directional RNNs. Not for GRU.")
add_arg('infer_manifest',   str,
        'datasets/manifest.dev',
        "Filepath of manifest to infer.")
add_arg('mean_std_path',    str,
        'mean_std.npz',
        "Filepath of normalizer's mean & std.")
add_arg('vocab_path',       str,
        'datasets/vocab/eng_vocab.txt',
        "Filepath of vocabulary.")
49 50 51
add_arg('lang_model_path',  str,
        'lm/data/common_crawl_00.prune01111.trie.klm',
        "Filepath for language model.")
52 53 54 55
add_arg('model_path',       str,
        './checkpoints/params.latest.tar.gz',
        "If None, the training starts from scratch, "
        "otherwise, it resumes from the pre-trained model.")
56 57 58 59 60 61 62 63 64 65 66 67
add_arg('decoder_method',   str,
        'ctc_beam_search',
        "Decoder method. Options: ctc_beam_search, ctc_greedy",
        choices = ['ctc_beam_search', 'ctc_greedy'])
add_arg('error_rate_type',  str,
        'wer',
        "Error rate type for evaluation.",
        choices=['wer', 'cer'])
add_arg('specgram_type',    str,
        'linear',
        "Audio feature type. Options: linear, mfcc.",
        choices=['linear', 'mfcc'])
68
args = parser.parse_args()
69
# yapf: disable
70 71


72
def infer():
Y
Yibing Liu 已提交
73
    """Inference for DeepSpeech2."""
74
    data_generator = DataGenerator(
75 76
        vocab_filepath=args.vocab_path,
        mean_std_filepath=args.mean_std_path,
77
        augmentation_config='{}',
78
        specgram_type=args.specgram_type,
79
        num_threads=1)
80
    batch_reader = data_generator.batch_reader_creator(
81
        manifest_path=args.infer_manifest,
82
        batch_size=args.num_samples,
Y
Yibing Liu 已提交
83
        min_batch_size=1,
84
        sortagrad=False,
85
        shuffle_method=None)
86
    infer_data = batch_reader().next()
87

88 89 90 91 92
    ds2_model = DeepSpeech2Model(
        vocab_size=data_generator.vocab_size,
        num_conv_layers=args.num_conv_layers,
        num_rnn_layers=args.num_rnn_layers,
        rnn_layer_size=args.rnn_layer_size,
X
Xinghai Sun 已提交
93
        use_gru=args.use_gru,
94
        pretrained_model_path=args.model_path,
95
        share_rnn_weights=args.share_rnn_weights)
96 97
    result_transcripts = ds2_model.infer_batch(
        infer_data=infer_data,
98
        decoder_method=args.decoder_method,
99 100 101 102 103
        beam_alpha=args.alpha,
        beam_beta=args.beta,
        beam_size=args.beam_size,
        cutoff_prob=args.cutoff_prob,
        vocab_list=data_generator.vocab_list,
104 105
        language_model_path=args.lang_model_path,
        num_processes=args.parallels_bsearch)
106

Y
yangyaming 已提交
107
    error_rate_func = cer if args.error_rate_type == 'cer' else wer
108 109 110
    target_transcripts = [
        ''.join([data_generator.vocab_list[token] for token in transcript])
        for _, transcript in infer_data
Y
Yibing Liu 已提交
111
    ]
112 113 114
    for target, result in zip(target_transcripts, result_transcripts):
        print("\nTarget Transcription: %s\nOutput Transcription: %s" %
              (target, result))
Y
yangyaming 已提交
115 116
        print("Current error rate [%s] = %f" %
              (args.error_rate_type, error_rate_func(target, result)))
117 118


119 120 121 122 123 124 125
def print_arguments(args):
    print("-----------  Configuration Arguments -----------")
    for arg, value in sorted(vars(args).iteritems()):
        print("%s: %s" % (arg, value))
    print("------------------------------------------------")


126
def main():
127
    print_arguments(args)
128
    paddle.init(use_gpu=args.use_gpu, trainer_count=args.trainer_count)
129
    infer()
130 131 132 133


if __name__ == '__main__':
    main()