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
import distutils.util
9
import multiprocessing
10 11
import paddle.v2 as paddle
from data_utils.data import DataGenerator
X
Xinghai Sun 已提交
12
from model import deep_speech2
13
from decoder import ctc_decode
14
import utils
15

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


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

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

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

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

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

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


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


if __name__ == '__main__':
    main()