infer.py 12.9 KB
Newer Older
K
KP 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import os
H
huangyuxin 已提交
16
import sys
K
KP 已提交
17 18 19 20
from typing import List
from typing import Optional
from typing import Union

H
huangyuxin 已提交
21
import soundfile
K
KP 已提交
22
import paddle
H
huangyuxin 已提交
23 24 25 26 27 28 29 30 31 32 33
from paddlespeech.cli.executor import BaseExecutor
from paddlespeech.cli.utils import cli_register
from paddlespeech.cli.utils import download_and_decompress
from paddlespeech.cli.utils import logger
from paddlespeech.cli.utils import MODEL_HOME
from paddlespeech.s2t.exps.u2.config import get_cfg_defaults
from paddlespeech.s2t.frontend.featurizer.text_featurizer import TextFeaturizer
from paddlespeech.s2t.io.collator import SpeechCollator
from paddlespeech.s2t.transform.transformation import Transformation
from paddlespeech.s2t.utils.dynamic_import import dynamic_import
from paddlespeech.s2t.utils.utility import UpdateConfig
K
KP 已提交
34 35 36

__all__ = ['S2TExecutor']

K
KP 已提交
37 38 39 40 41 42
pretrained_models = {
    "wenetspeech_zh": {
        'url':
        'https://paddlespeech.bj.bcebos.com/s2t/wenetspeech/conformer.model.tar.gz',
        'md5':
        '54e7a558a6e020c2f5fb224874943f97',
H
huangyuxin 已提交
43 44 45 46
        'cfg_path':
        'conf/conformer.yaml',
        'ckpt_path':
        'exp/conformer/checkpoints/wenetspeech',
K
KP 已提交
47 48 49
    }
}

H
huangyuxin 已提交
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 75 76 77 78 79 80
model_alias = {
    "ds2_offline": "paddlespeech.s2t.models.ds2:DeepSpeech2Model",
    "ds2_online": "paddlespeech.s2t.models.ds2_online:DeepSpeech2ModelOnline",
    "conformer": "paddlespeech.s2t.models.u2:U2Model",
    "transformer": "paddlespeech.s2t.models.u2:U2Model",
    "wenetspeech": "paddlespeech.s2t.models.u2:U2Model",
}

pretrain_model_alias = {
    "ds2_online_zn": [
        "https://paddlespeech.bj.bcebos.com/s2t/aishell/asr0/aishell_ds2_online_cer8.00_release.tar.gz",
        "", ""
    ],
    "ds2_offline_zn": [
        "https://paddlespeech.bj.bcebos.com/s2t/aishell/asr0/ds2.model.tar.gz",
        "", ""
    ],
    "transformer_zn": [
        "https://paddlespeech.bj.bcebos.com/s2t/aishell/asr1/transformer.model.tar.gz",
        "", ""
    ],
    "conformer_zn": [
        "https://paddlespeech.bj.bcebos.com/s2t/wenetspeech/conformer.model.tar.gz",
        "", ""
    ],
    "wenetspeech_zn": [
        "https://paddlespeech.bj.bcebos.com/s2t/wenetspeech/conformer.model.tar.gz",
        "conf/conformer.yaml", "exp/conformer/checkpoints/wenetspeech"
    ],
}

K
KP 已提交
81

K
KP 已提交
82 83
@cli_register(
    name='paddlespeech.s2t', description='Speech to text infer command.')
K
KP 已提交
84 85 86 87 88 89
class S2TExecutor(BaseExecutor):
    def __init__(self):
        super(S2TExecutor, self).__init__()

        self.parser = argparse.ArgumentParser(
            prog='paddlespeech.s2t', add_help=True)
K
KP 已提交
90 91 92 93 94 95 96
        self.parser.add_argument(
            '--model',
            type=str,
            default='wenetspeech',
            help='Choose model type of asr task.')
        self.parser.add_argument(
            '--lang', type=str, default='zh', help='Choose model language.')
K
KP 已提交
97 98 99 100 101
        self.parser.add_argument(
            '--config',
            type=str,
            default=None,
            help='Config of s2t task. Use deault config when it is None.')
K
KP 已提交
102 103 104 105 106
        self.parser.add_argument(
            '--ckpt_path',
            type=str,
            default=None,
            help='Checkpoint file of model.')
K
KP 已提交
107
        self.parser.add_argument(
H
huangyuxin 已提交
108 109 110 111
            '--input',
            type=str,
            default="../Downloads/asr-demo-1.wav",
            help='Audio file to recognize.')
K
KP 已提交
112 113 114 115 116 117
        self.parser.add_argument(
            '--device',
            type=str,
            default='cpu',
            help='Choose device to execute model inference.')

K
KP 已提交
118
    def _get_pretrained_path(self, tag: str) -> os.PathLike:
K
KP 已提交
119
        """
K
KP 已提交
120
            Download and returns pretrained resources path of current task.
K
KP 已提交
121
        """
K
KP 已提交
122 123 124 125 126 127
        assert tag in pretrained_models, 'Can not find pretrained resources of {}.'.format(
            tag)

        res_path = os.path.join(MODEL_HOME, tag)
        decompressed_path = download_and_decompress(pretrained_models[tag],
                                                    res_path)
H
huangyuxin 已提交
128
        decompressed_path = os.path.abspath(decompressed_path)
K
KP 已提交
129 130
        logger.info(
            'Use pretrained model stored in: {}'.format(decompressed_path))
H
huangyuxin 已提交
131

K
KP 已提交
132
        return decompressed_path
K
KP 已提交
133

K
KP 已提交
134 135 136 137 138
    def _init_from_path(self,
                        model_type: str='wenetspeech',
                        lang: str='zh',
                        cfg_path: Optional[os.PathLike]=None,
                        ckpt_path: Optional[os.PathLike]=None):
K
KP 已提交
139
        """
K
KP 已提交
140
            Init model and other resources from a specific path.
K
KP 已提交
141
        """
K
KP 已提交
142
        if cfg_path is None or ckpt_path is None:
H
huangyuxin 已提交
143 144 145 146 147 148
            tag = model_type + '_' + lang
            res_path = self._get_pretrained_path(tag)  # wenetspeech_zh
            self.cfg_path = os.path.join(res_path,
                                         pretrained_models[tag]['cfg_path'])
            self.ckpt_path = os.path.join(res_path,
                                          pretrained_models[tag]['ckpt_path'])
K
KP 已提交
149
            logger.info(res_path)
H
huangyuxin 已提交
150 151 152 153 154 155 156
            logger.info(self.cfg_path)
            logger.info(self.ckpt_path)
        else:
            self.cfg_path = os.path.abspath(cfg_path)
            self.ckpt_path = os.path.abspath(ckpt_path)
            res_path = os.path.dirname(
                os.path.dirname(os.path.abspath(self.cfg_path)))
K
KP 已提交
157

H
huangyuxin 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
        os.chdir(res_path)
        #Init body.
        parser_args = self.parser_args
        paddle.set_device(parser_args.device)
        self.config = get_cfg_defaults()
        self.config.merge_from_file(self.cfg_path)
        self.config.decoding.decoding_method = "attention_rescoring"
        #self.config.freeze()
        model_conf = self.config.model
        logger.info(model_conf)

        with UpdateConfig(model_conf):
            if parser_args.model == "ds2_online" or parser_args.model == "ds2_offline":
                self.config.collator.vocab_filepath = os.path.join(
                    res_path, self.config.collator.vocab_filepath)
                self.config.collator.vocab_filepath = os.path.join(
                    res_path, self.config.collator.cmvn_path)
                self.collate_fn_test = SpeechCollator.from_config(self.config)
                model_conf.feat_size = self.collate_fn_test.feature_size
                model_conf.dict_size = self.text_feature.vocab_size
            elif parser_args.model == "conformer" or parser_args.model == "transformer" or parser_args.model == "wenetspeech":
                self.config.collator.vocab_filepath = os.path.join(
                    res_path, self.config.collator.vocab_filepath)
                self.text_feature = TextFeaturizer(
                    unit_type=self.config.collator.unit_type,
                    vocab_filepath=self.config.collator.vocab_filepath,
                    spm_model_prefix=self.config.collator.spm_model_prefix)
                model_conf.input_dim = self.config.collator.feat_dim
                model_conf.output_dim = self.text_feature.vocab_size
            else:
                raise Exception("wrong type")
        model_class = dynamic_import(parser_args.model, model_alias)
        model = model_class.from_config(model_conf)
        self.model = model
        self.model.eval()

        # load model
        params_path = self.ckpt_path + ".pdparams"
        model_dict = paddle.load(params_path)
        self.model.set_state_dict(model_dict)
K
KP 已提交
198 199 200 201 202 203

    def preprocess(self, input: Union[str, os.PathLike]):
        """
            Input preprocess and return paddle.Tensor stored in self.input.
            Input content can be a text(t2s), a file(s2t, cls) or a streaming(not supported yet).
        """
H
huangyuxin 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252

        parser_args = self.parser_args
        config = self.config
        audio_file = input
        #print("audio_file", audio_file)
        logger.info("audio_file"+ audio_file)

        self.sr = config.collator.target_sample_rate

        # Get the object for feature extraction
        if parser_args.model == "ds2_online" or parser_args.model == "ds2_offline":
            audio, _ = collate_fn_test.process_utterance(
                audio_file=audio_file, transcript=" ")
            audio_len = audio.shape[0]
            audio = paddle.to_tensor(audio, dtype='float32')
            self.audio_len = paddle.to_tensor(audio_len)
            self.audio = paddle.unsqueeze(audio, axis=0)
            self.vocab_list = collate_fn_test.vocab_list
            logger.info(f"audio feat shape: {self.audio.shape}")

        elif parser_args.model == "conformer" or parser_args.model == "transformer" or parser_args.model == "wenetspeech":
            logger.info("get the preprocess conf")
            preprocess_conf = os.path.join(
                os.path.dirname(os.path.abspath(self.cfg_path)),
                "preprocess.yaml")

            cmvn_path: data / mean_std.json

            logger.info(preprocess_conf)
            preprocess_args = {"train": False}
            preprocessing = Transformation(preprocess_conf)
            audio, sample_rate = soundfile.read(
                audio_file, dtype="int16", always_2d=True)
            if sample_rate != self.sr:
                logger.error(
                    f"sample rate error: {sample_rate}, need {self.sr} ")
                sys.exit(-1)
            audio = audio[:, 0]
            logger.info(f"audio shape: {audio.shape}")
            # fbank
            audio = preprocessing(audio, **preprocess_args)

            self.audio_len = paddle.to_tensor(audio.shape[0])
            self.audio = paddle.to_tensor(
                audio, dtype='float32').unsqueeze(axis=0)
            logger.info(f"audio feat shape: {self.audio.shape}")

        else:
            raise Exception("wrong type")
K
KP 已提交
253 254 255 256 257 258

    @paddle.no_grad()
    def infer(self):
        """
            Model inference and result stored in self.output.
        """
H
huangyuxin 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
        cfg = self.config.decoding
        parser_args = self.parser_args
        audio = self.audio
        audio_len = self.audio_len
        if parser_args.model == "ds2_online" or parser_args.model == "ds2_offline":
            vocab_list = self.vocab_list
            result_transcripts = self.model.decode(
                audio,
                audio_len,
                vocab_list,
                decoding_method=cfg.decoding_method,
                lang_model_path=cfg.lang_model_path,
                beam_alpha=cfg.alpha,
                beam_beta=cfg.beta,
                beam_size=cfg.beam_size,
                cutoff_prob=cfg.cutoff_prob,
                cutoff_top_n=cfg.cutoff_top_n,
                num_processes=cfg.num_proc_bsearch)
            self.result_transcripts = result_transcripts[0]

        elif parser_args.model == "conformer" or parser_args.model == "transformer" or parser_args.model == "wenetspeech":
            text_feature = self.text_feature
            result_transcripts = self.model.decode(
                audio,
                audio_len,
                text_feature=self.text_feature,
                decoding_method=cfg.decoding_method,
                lang_model_path=cfg.lang_model_path,
                beam_alpha=cfg.alpha,
                beam_beta=cfg.beta,
                beam_size=cfg.beam_size,
                cutoff_prob=cfg.cutoff_prob,
                cutoff_top_n=cfg.cutoff_top_n,
                num_processes=cfg.num_proc_bsearch,
                ctc_weight=cfg.ctc_weight,
                decoding_chunk_size=cfg.decoding_chunk_size,
                num_decoding_left_chunks=cfg.num_decoding_left_chunks,
                simulate_streaming=cfg.simulate_streaming)
            self.result_transcripts = result_transcripts[0][0]
        else:
            raise Exception("invalid model name")

K
KP 已提交
301 302 303 304 305 306
        pass

    def postprocess(self) -> Union[str, os.PathLike]:
        """
            Output postprocess and return human-readable results such as texts and audio files.
        """
H
huangyuxin 已提交
307
        return self.result_transcripts
K
KP 已提交
308 309

    def execute(self, argv: List[str]) -> bool:
H
huangyuxin 已提交
310
        self.parser_args = self.parser.parse_args(argv)
K
KP 已提交
311

H
huangyuxin 已提交
312 313 314 315 316 317
        model = self.parser_args.model
        lang = self.parser_args.lang
        config = self.parser_args.config
        ckpt_path = self.parser_args.ckpt_path
        audio_file = os.path.abspath(self.parser_args.input)
        device = self.parser_args.device
K
KP 已提交
318 319

        try:
K
KP 已提交
320
            self._init_from_path(model, lang, config, ckpt_path)
K
KP 已提交
321 322 323
            self.preprocess(audio_file)
            self.infer()
            res = self.postprocess()  # Retrieve result of s2t.
H
huangyuxin 已提交
324
            logger.info(res)
K
KP 已提交
325 326 327 328
            return True
        except Exception as e:
            print(e)
            return False
H
huangyuxin 已提交
329 330 331 332 333


if __name__ == "__main__":
    exe = S2TExecutor()
    exe.execute('')