infer.py 4.2 KB
Newer Older
1
"""Inferer for DeepSpeech2 model."""
2 3 4 5
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

6 7
import argparse
import gzip
8 9 10
import distutils.util
import paddle.v2 as paddle
from data_utils.data import DataGenerator
X
Xinghai Sun 已提交
11
from model import deep_speech2
12
from decoder import ctc_decode
13
import utils
14

15
parser = argparse.ArgumentParser(description=__doc__)
16
parser.add_argument(
X
Xinghai Sun 已提交
17 18 19
    "--num_samples",
    default=10,
    type=int,
20
    help="Number of samples for inference. (default: %(default)s)")
21
parser.add_argument(
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
    "--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)")
41 42 43 44 45
parser.add_argument(
    "--num_threads_data",
    default=12,
    type=int,
    help="Number of cpu threads for preprocessing data. (default: %(default)s)")
46
parser.add_argument(
47 48
    "--mean_std_filepath",
    default='mean_std.npz',
49 50
    type=str,
    help="Manifest path for normalizer. (default: %(default)s)")
51
parser.add_argument(
52
    "--decode_manifest_path",
53
    default='datasets/manifest.test',
54 55
    type=str,
    help="Manifest path for decoding. (default: %(default)s)")
56
parser.add_argument(
57 58 59 60
    "--model_filepath",
    default='./params.tar.gz',
    type=str,
    help="Model filepath. (default: %(default)s)")
61 62
parser.add_argument(
    "--vocab_filepath",
63
    default='datasets/vocab/eng_vocab.txt',
64 65
    type=str,
    help="Vocabulary filepath. (default: %(default)s)")
66 67 68
args = parser.parse_args()


69
def infer():
70
    """Max-ctc-decoding for DeepSpeech2."""
71 72
    # initialize data generator
    data_generator = DataGenerator(
73
        vocab_filepath=args.vocab_filepath,
74
        mean_std_filepath=args.mean_std_filepath,
75 76
        augmentation_config='{}',
        num_threads=args.num_threads_data)
77

78
    # create network config
79 80 81
    # 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.
82
    audio_data = paddle.layer.data(
83
        name="audio_spectrogram", type=paddle.data_type.dense_array(161 * 161))
84 85
    text_data = paddle.layer.data(
        name="transcript_text",
86
        type=paddle.data_type.integer_value_sequence(data_generator.vocab_size))
87
    output_probs = deep_speech2(
88 89
        audio_data=audio_data,
        text_data=text_data,
90
        dict_size=data_generator.vocab_size,
91 92
        num_conv_layers=args.num_conv_layers,
        num_rnn_layers=args.num_rnn_layers,
93 94
        rnn_size=args.rnn_layer_size,
        is_inference=True)
95 96 97

    # load parameters
    parameters = paddle.parameters.Parameters.from_tar(
98
        gzip.open(args.model_filepath))
99 100

    # prepare infer data
101
    batch_reader = data_generator.batch_reader_creator(
102 103
        manifest_path=args.decode_manifest_path,
        batch_size=args.num_samples,
104
        sortagrad=False,
105
        shuffle_method=None)
106
    infer_data = batch_reader().next()
107

108 109 110
    # run inference
    infer_results = paddle.infer(
        output_layer=output_probs, parameters=parameters, input=infer_data)
111
    num_steps = len(infer_results) // len(infer_data)
112 113
    probs_split = [
        infer_results[i * num_steps:(i + 1) * num_steps]
114
        for i in xrange(len(infer_data))
115
    ]
116 117 118 119

    # decode and print
    for i, probs in enumerate(probs_split):
        output_transcription = ctc_decode(
120 121 122
            probs_seq=probs,
            vocabulary=data_generator.vocab_list,
            method="best_path")
123
        target_transcription = ''.join(
124
            [data_generator.vocab_list[index] for index in infer_data[i][1]])
125 126
        print("Target Transcription: %s \nOutput Transcription: %s \n" %
              (target_transcription, output_transcription))
127 128 129


def main():
130
    utils.print_arguments(args)
131
    paddle.init(use_gpu=args.use_gpu, trainer_count=1)
132
    infer()
133 134 135 136


if __name__ == '__main__':
    main()