infer.py 4.6 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
X
Xinghai Sun 已提交
7
import functools
8 9
import paddle.v2 as paddle
from data_utils.data import DataGenerator
10 11 12
from models.model import DeepSpeech2Model
from utils.error_rate import wer, cer
from utils.utility import add_arguments, print_arguments
13

14
parser = argparse.ArgumentParser(description=__doc__)
X
Xinghai Sun 已提交
15 16
add_arg = functools.partial(add_arguments, argparser=parser)
# yapf: disable
17 18 19
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.")
20
add_arg('num_proc_bsearch', int,    12,     "# of CPUs for beam search.")
21 22 23
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.")
24 25 26
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.")
27
add_arg('use_gru',          bool,   False,  "Use GRUs instead of simple RNNs.")
28
add_arg('use_gpu',          bool,   True,   "Use GPU or not.")
29 30 31
add_arg('share_rnn_weights',bool,   True,   "Share input-hidden weights across "
                                            "bi-directional RNNs. Not for GRU.")
add_arg('infer_manifest',   str,
32
        'data/librispeech/manifest.dev-clean',
33 34
        "Filepath of manifest to infer.")
add_arg('mean_std_path',    str,
35
        'data/librispeech/mean_std.npz',
36 37
        "Filepath of normalizer's mean & std.")
add_arg('vocab_path',       str,
38
        'data/librispeech/eng_vocab.txt',
39
        "Filepath of vocabulary.")
40 41 42
add_arg('lang_model_path',  str,
        'lm/data/common_crawl_00.prune01111.trie.klm',
        "Filepath for language model.")
43 44 45 46
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.")
47
add_arg('decoding_method',  str,
48
        'ctc_beam_search',
49
        "Decoding method. Options: ctc_beam_search, ctc_greedy",
50 51 52 53 54 55 56 57 58
        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'])
59
# yapf: disable
X
Xinghai Sun 已提交
60
args = parser.parse_args()
61 62


63
def infer():
Y
Yibing Liu 已提交
64
    """Inference for DeepSpeech2."""
65
    data_generator = DataGenerator(
66 67
        vocab_filepath=args.vocab_path,
        mean_std_filepath=args.mean_std_path,
68
        augmentation_config='{}',
69
        specgram_type=args.specgram_type,
70
        num_threads=1)
71
    batch_reader = data_generator.batch_reader_creator(
72
        manifest_path=args.infer_manifest,
73
        batch_size=args.num_samples,
Y
Yibing Liu 已提交
74
        min_batch_size=1,
75
        sortagrad=False,
76
        shuffle_method=None)
77
    infer_data = batch_reader().next()
78

79 80 81 82 83
    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 已提交
84
        use_gru=args.use_gru,
85
        pretrained_model_path=args.model_path,
86
        share_rnn_weights=args.share_rnn_weights)
87 88
    result_transcripts = ds2_model.infer_batch(
        infer_data=infer_data,
89
        decoding_method=args.decoding_method,
90 91 92 93 94
        beam_alpha=args.alpha,
        beam_beta=args.beta,
        beam_size=args.beam_size,
        cutoff_prob=args.cutoff_prob,
        vocab_list=data_generator.vocab_list,
95
        language_model_path=args.lang_model_path,
96
        num_processes=args.num_proc_bsearch)
97

Y
yangyaming 已提交
98
    error_rate_func = cer if args.error_rate_type == 'cer' else wer
99 100 101
    target_transcripts = [
        ''.join([data_generator.vocab_list[token] for token in transcript])
        for _, transcript in infer_data
Y
Yibing Liu 已提交
102
    ]
103 104 105
    for target, result in zip(target_transcripts, result_transcripts):
        print("\nTarget Transcription: %s\nOutput Transcription: %s" %
              (target, result))
Y
yangyaming 已提交
106 107
        print("Current error rate [%s] = %f" %
              (args.error_rate_type, error_rate_func(target, result)))
108 109 110


def main():
111
    print_arguments(args)
112
    paddle.init(use_gpu=args.use_gpu, trainer_count=args.trainer_count)
113
    infer()
114 115 116 117


if __name__ == '__main__':
    main()