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

14
NUM_CPU = multiprocessing.cpu_count() // 2
15
parser = argparse.ArgumentParser(description=__doc__)
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74


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
# configurations of overall
add_arg('num_samples',      int,    10,     "# of samples to infer.")
add_arg('trainer_count',    int,    8,      "# of Trainers (CPUs or GPUs).")
add_arg('use_gpu',          bool,   True,   "Use GPU or not.")
add_arg('error_rate_type',  str,    'wer',  "Error rate type for evaluation.",
        choices=['wer', 'cer'])
# configurations of decoder
add_arg('beam_size',        int,    500,    "Beam search width.")
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.")
add_arg('parallels_bsearch',int,    NUM_CPU,"# of CPUs for beam search.")
add_arg('lang_model_path',  str,
        'lm/data/common_crawl_00.prune01111.trie.klm',
        "Filepath for language model.")
add_arg('decoder_method',   str,
        'ctc_beam_search',
        "Decoder method. Options: ctc_beam_search, ctc_greedy",
        choices = ['ctc_beam_search', 'ctc_greedy'])
# configurations of data preprocess
add_arg('specgram_type',    str,
        'linear',
        "Audio feature type. Options: linear, mfcc.",
        choices=['linear', 'mfcc'])
# configurations of model structure
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.")
add_arg('use_gru',          bool,   False,  "Use GRUs instead of Simple RNNs.")
add_arg('share_rnn_weights',bool,   True,   "Share input-hidden weights across "
                                            "bi-directional RNNs. Not for GRU.")
# configurations of data io
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.")
# configurations of model io
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.")
75
args = parser.parse_args()
76
# yapf: disable
77 78


79
def infer():
Y
Yibing Liu 已提交
80
    """Inference for DeepSpeech2."""
81
    data_generator = DataGenerator(
82 83
        vocab_filepath=args.vocab_path,
        mean_std_filepath=args.mean_std_path,
84
        augmentation_config='{}',
85
        specgram_type=args.specgram_type,
86
        num_threads=1)
87
    batch_reader = data_generator.batch_reader_creator(
88
        manifest_path=args.infer_manifest,
89
        batch_size=args.num_samples,
Y
Yibing Liu 已提交
90
        min_batch_size=1,
91
        sortagrad=False,
92
        shuffle_method=None)
93
    infer_data = batch_reader().next()
94

95 96 97 98 99
    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 已提交
100
        use_gru=args.use_gru,
101
        pretrained_model_path=args.model_path,
102
        share_rnn_weights=args.share_rnn_weights)
103 104
    result_transcripts = ds2_model.infer_batch(
        infer_data=infer_data,
105
        decoder_method=args.decoder_method,
106 107 108 109 110
        beam_alpha=args.alpha,
        beam_beta=args.beta,
        beam_size=args.beam_size,
        cutoff_prob=args.cutoff_prob,
        vocab_list=data_generator.vocab_list,
111 112
        language_model_path=args.lang_model_path,
        num_processes=args.parallels_bsearch)
113

Y
yangyaming 已提交
114
    error_rate_func = cer if args.error_rate_type == 'cer' else wer
115 116 117
    target_transcripts = [
        ''.join([data_generator.vocab_list[token] for token in transcript])
        for _, transcript in infer_data
Y
Yibing Liu 已提交
118
    ]
119 120 121
    for target, result in zip(target_transcripts, result_transcripts):
        print("\nTarget Transcription: %s\nOutput Transcription: %s" %
              (target, result))
Y
yangyaming 已提交
122 123
        print("Current error rate [%s] = %f" %
              (args.error_rate_type, error_rate_func(target, result)))
124 125


126 127 128 129 130 131 132
def print_arguments(args):
    print("-----------  Configuration Arguments -----------")
    for arg, value in sorted(vars(args).iteritems()):
        print("%s: %s" % (arg, value))
    print("------------------------------------------------")


133
def main():
134
    print_arguments(args)
135
    paddle.init(use_gpu=args.use_gpu, trainer_count=args.trainer_count)
136
    infer()
137 138 139 140


if __name__ == '__main__':
    main()