infer.py 4.8 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
from model_utils.model import DeepSpeech2Model
11 12
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.")
Y
Yibing Liu 已提交
24 25
add_arg('alpha',            float,  2.15,   "Coef of LM for beam search.")
add_arg('beta',             float,  0.35,   "Coef of WC for beam search.")
Y
Yibing Liu 已提交
26 27
add_arg('cutoff_prob',      float,  1.0,    "Cutoff probability for pruning.")
add_arg('cutoff_top_n',     int,    40,     "Cutoff number for pruning.")
28
add_arg('use_gru',          bool,   False,  "Use GRUs instead of simple RNNs.")
29
add_arg('use_gpu',          bool,   True,   "Use GPU or not.")
30 31 32
add_arg('share_rnn_weights',bool,   True,   "Share input-hidden weights across "
                                            "bi-directional RNNs. Not for GRU.")
add_arg('infer_manifest',   str,
33
        'data/librispeech/manifest.dev-clean',
34 35
        "Filepath of manifest to infer.")
add_arg('mean_std_path',    str,
36
        'data/librispeech/mean_std.npz',
37 38
        "Filepath of normalizer's mean & std.")
add_arg('vocab_path',       str,
39
        'data/librispeech/vocab.txt',
40
        "Filepath of vocabulary.")
41
add_arg('lang_model_path',  str,
42
        'models/lm/common_crawl_00.prune01111.trie.klm',
43
        "Filepath for language model.")
44
add_arg('model_path',       str,
45
        './checkpoints/libri/params.latest.tar.gz',
46 47
        "If None, the training starts from scratch, "
        "otherwise, it resumes from the pre-trained model.")
48
add_arg('decoding_method',  str,
49
        'ctc_beam_search',
50
        "Decoding method. Options: ctc_beam_search, ctc_greedy",
51 52 53 54 55 56 57 58 59
        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'])
60
# yapf: disable
X
Xinghai Sun 已提交
61
args = parser.parse_args()
62 63


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

80 81 82 83 84
    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 已提交
85
        use_gru=args.use_gru,
86
        pretrained_model_path=args.model_path,
87
        share_rnn_weights=args.share_rnn_weights)
88

Y
Yibing Liu 已提交
89 90 91
    # decoders only accept string encoded in utf-8
    vocab_list = [chars.encode("utf-8") for chars in data_generator.vocab_list]

92 93
    result_transcripts = ds2_model.infer_batch(
        infer_data=infer_data,
94
        decoding_method=args.decoding_method,
95 96 97 98
        beam_alpha=args.alpha,
        beam_beta=args.beta,
        beam_size=args.beam_size,
        cutoff_prob=args.cutoff_prob,
Y
Yibing Liu 已提交
99 100
        cutoff_top_n=args.cutoff_top_n,
        vocab_list=vocab_list,
101
        language_model_path=args.lang_model_path,
102
        num_processes=args.num_proc_bsearch)
103

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


def main():
117
    print_arguments(args)
118
    paddle.init(use_gpu=args.use_gpu, trainer_count=args.trainer_count)
119
    infer()
120 121 122 123


if __name__ == '__main__':
    main()