infer.py 16.4 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 librosa
K
KP 已提交
22
import paddle
H
huangyuxin 已提交
23
import soundfile
H
huangyuxin 已提交
24
from yacs.config import CfgNode
K
KP 已提交
25 26 27

from ..executor import BaseExecutor
from ..utils import cli_register
K
KP 已提交
28 29 30
from ..utils import download_and_decompress
from ..utils import logger
from ..utils import MODEL_HOME
H
huangyuxin 已提交
31 32 33 34
from paddlespeech.s2t.frontend.featurizer.text_featurizer import TextFeaturizer
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 已提交
35

K
KP 已提交
36
__all__ = ['ASRExecutor']
K
KP 已提交
37

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

H
huangyuxin 已提交
51 52 53 54 55 56 57 58
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",
}

K
KP 已提交
59

K
KP 已提交
60
@cli_register(
K
KP 已提交
61 62
    name='paddlespeech.asr', description='Speech to text infer command.')
class ASRExecutor(BaseExecutor):
K
KP 已提交
63
    def __init__(self):
K
KP 已提交
64
        super(ASRExecutor, self).__init__()
K
KP 已提交
65 66

        self.parser = argparse.ArgumentParser(
K
KP 已提交
67 68 69
            prog='paddlespeech.asr', add_help=True)
        self.parser.add_argument(
            '--input', type=str, required=True, help='Audio file to recognize.')
K
KP 已提交
70 71 72 73 74 75
        self.parser.add_argument(
            '--model',
            type=str,
            default='wenetspeech',
            help='Choose model type of asr task.')
        self.parser.add_argument(
H
huangyuxin 已提交
76 77 78 79 80
            '--lang',
            type=str,
            default='zh',
            help='Choose model language. zh or en')
        self.parser.add_argument(
H
huangyuxin 已提交
81
            "--sr",
H
huangyuxin 已提交
82 83 84
            type=int,
            default=16000,
            help='Choose the audio sample rate of the model. 8000 or 16000')
K
KP 已提交
85 86 87 88
        self.parser.add_argument(
            '--config',
            type=str,
            default=None,
K
KP 已提交
89
            help='Config of asr task. Use deault config when it is None.')
K
KP 已提交
90 91 92 93 94
        self.parser.add_argument(
            '--ckpt_path',
            type=str,
            default=None,
            help='Checkpoint file of model.')
K
KP 已提交
95 96 97
        self.parser.add_argument(
            '--device',
            type=str,
K
KP 已提交
98
            default=paddle.get_device(),
K
KP 已提交
99 100
            help='Choose device to execute model inference.')

K
KP 已提交
101
    def _get_pretrained_path(self, tag: str) -> os.PathLike:
K
KP 已提交
102
        """
K
KP 已提交
103
            Download and returns pretrained resources path of current task.
K
KP 已提交
104
        """
K
KP 已提交
105 106 107 108 109 110
        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 已提交
111
        decompressed_path = os.path.abspath(decompressed_path)
K
KP 已提交
112 113
        logger.info(
            'Use pretrained model stored in: {}'.format(decompressed_path))
H
huangyuxin 已提交
114

K
KP 已提交
115
        return decompressed_path
K
KP 已提交
116

K
KP 已提交
117 118 119
    def _init_from_path(self,
                        model_type: str='wenetspeech',
                        lang: str='zh',
H
huangyuxin 已提交
120
                        sample_rate: int=16000,
K
KP 已提交
121
                        cfg_path: Optional[os.PathLike]=None,
H
revise  
huangyuxin 已提交
122 123
                        ckpt_path: Optional[os.PathLike]=None
                        ):
K
KP 已提交
124
        """
K
KP 已提交
125
            Init model and other resources from a specific path.
K
KP 已提交
126
        """
K
KP 已提交
127
        if cfg_path is None or ckpt_path is None:
H
huangyuxin 已提交
128 129
            sample_rate_str = '16k' if sample_rate == 16000 else '8k'
            tag = model_type + '_' + lang + '_' + sample_rate_str
H
huangyuxin 已提交
130 131 132 133 134
            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 已提交
135
            logger.info(res_path)
H
huangyuxin 已提交
136 137 138 139 140 141 142
            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 已提交
143

H
huangyuxin 已提交
144
        #Init body.
H
huangyuxin 已提交
145
        self.config = CfgNode(new_allowed=True)
H
huangyuxin 已提交
146 147 148 149 150 151
        self.config.merge_from_file(self.cfg_path)
        self.config.decoding.decoding_method = "attention_rescoring"
        model_conf = self.config.model
        logger.info(model_conf)

        with UpdateConfig(model_conf):
H
huangyuxin 已提交
152
            if model_type == "ds2_online" or model_type == "ds2_offline":
H
huangyuxin 已提交
153
                from paddlespeech.s2t.io.collator import SpeechCollator
H
huangyuxin 已提交
154 155
                self.config.collator.vocab_filepath = os.path.join(
                    res_path, self.config.collator.vocab_filepath)
H
huangyuxin 已提交
156
                self.config.collator.mean_std_filepath = os.path.join(
H
huangyuxin 已提交
157 158
                    res_path, self.config.collator.cmvn_path)
                self.collate_fn_test = SpeechCollator.from_config(self.config)
H
huangyuxin 已提交
159 160 161 162
                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)
H
huangyuxin 已提交
163
                model_conf.input_dim = self.collate_fn_test.feature_size
H
huangyuxin 已提交
164 165
                model_conf.output_dim = text_feature.vocab_size
            elif model_type == "conformer" or model_type == "transformer" or model_type == "wenetspeech":
H
huangyuxin 已提交
166 167
                self.config.collator.vocab_filepath = os.path.join(
                    res_path, self.config.collator.vocab_filepath)
H
huangyuxin 已提交
168
                text_feature = TextFeaturizer(
H
huangyuxin 已提交
169 170 171 172
                    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
H
huangyuxin 已提交
173
                model_conf.output_dim = text_feature.vocab_size
H
huangyuxin 已提交
174 175
            else:
                raise Exception("wrong type")
H
huangyuxin 已提交
176
        self.config.freeze()
H
huangyuxin 已提交
177 178 179 180
        # Enter the path of model root
        os.chdir(res_path)

        model_class = dynamic_import(model_type, model_alias)
H
huangyuxin 已提交
181 182 183 184 185 186 187 188
        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 已提交
189

H
huangyuxin 已提交
190
    def preprocess(self, model_type: str, input: Union[str, os.PathLike]):
K
KP 已提交
191 192
        """
            Input preprocess and return paddle.Tensor stored in self.input.
K
KP 已提交
193
            Input content can be a text(tts), a file(asr, cls) or a streaming(not supported yet).
K
KP 已提交
194
        """
H
huangyuxin 已提交
195 196

        audio_file = input
H
huangyuxin 已提交
197
        logger.info("Preprocess audio_file:" + audio_file)
H
huangyuxin 已提交
198 199

        # Get the object for feature extraction
H
huangyuxin 已提交
200
        if model_type == "ds2_online" or model_type == "ds2_offline":
H
huangyuxin 已提交
201
            audio, _ = self.collate_fn_test.process_utterance(
H
huangyuxin 已提交
202 203 204
                audio_file=audio_file, transcript=" ")
            audio_len = audio.shape[0]
            audio = paddle.to_tensor(audio, dtype='float32')
H
huangyuxin 已提交
205 206 207 208 209 210 211 212
            audio_len = paddle.to_tensor(audio_len)
            audio = paddle.unsqueeze(audio, axis=0)
            vocab_list = collate_fn_test.vocab_list
            self._inputs["audio"] = audio
            self._inputs["audio_len"] = audio_len
            logger.info(f"audio feat shape: {audio.shape}")

        elif model_type == "conformer" or model_type == "transformer" or model_type == "wenetspeech":
H
huangyuxin 已提交
213 214 215 216 217 218 219 220
            logger.info("get the preprocess conf")
            preprocess_conf = os.path.join(
                os.path.dirname(os.path.abspath(self.cfg_path)),
                "preprocess.yaml")

            logger.info(preprocess_conf)
            preprocess_args = {"train": False}
            preprocessing = Transformation(preprocess_conf)
H
huangyuxin 已提交
221
            logger.info("read the audio file")
H
huangyuxin 已提交
222
            audio, audio_sample_rate = soundfile.read(
H
huangyuxin 已提交
223
                audio_file, dtype="int16", always_2d=True)
H
huangyuxin 已提交
224 225 226 227 228 229 230

            if self.change_format:
                if audio.shape[1] >= 2:
                    audio = audio.mean(axis=1)
                else:
                    audio = audio[:, 0]
                audio = audio.astype("float32")
H
huangyuxin 已提交
231 232 233
                audio = librosa.resample(audio, audio_sample_rate,
                                         self.sample_rate)
                audio_sample_rate = self.sample_rate
H
huangyuxin 已提交
234 235 236 237
                audio = audio.astype("int16")
            else:
                audio = audio[:, 0]

H
huangyuxin 已提交
238 239 240 241
            logger.info(f"audio shape: {audio.shape}")
            # fbank
            audio = preprocessing(audio, **preprocess_args)

H
huangyuxin 已提交
242 243 244 245 246 247 248 249 250
            audio_len = paddle.to_tensor(audio.shape[0])
            audio = paddle.to_tensor(audio, dtype='float32').unsqueeze(axis=0)
            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)
            self._inputs["audio"] = audio
            self._inputs["audio_len"] = audio_len
            logger.info(f"audio feat shape: {audio.shape}")
H
huangyuxin 已提交
251 252 253

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

    @paddle.no_grad()
H
huangyuxin 已提交
256
    def infer(self, model_type: str):
K
KP 已提交
257 258 259
        """
            Model inference and result stored in self.output.
        """
H
huangyuxin 已提交
260 261 262 263
        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)
H
huangyuxin 已提交
264
        cfg = self.config.decoding
H
huangyuxin 已提交
265 266 267
        audio = self._inputs["audio"]
        audio_len = self._inputs["audio_len"]
        if model_type == "ds2_online" or model_type == "ds2_offline":
H
huangyuxin 已提交
268 269 270
            result_transcripts = self.model.decode(
                audio,
                audio_len,
H
huangyuxin 已提交
271
                text_feature.vocab_list,
H
huangyuxin 已提交
272 273 274 275 276 277 278 279
                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)
H
huangyuxin 已提交
280
            self._outputs["result"] = result_transcripts[0]
H
huangyuxin 已提交
281

H
huangyuxin 已提交
282
        elif model_type == "conformer" or model_type == "transformer" or model_type == "wenetspeech":
H
huangyuxin 已提交
283 284 285
            result_transcripts = self.model.decode(
                audio,
                audio_len,
H
huangyuxin 已提交
286
                text_feature=text_feature,
H
huangyuxin 已提交
287 288 289 290 291 292 293 294 295 296 297 298
                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)
H
huangyuxin 已提交
299
            self._outputs["result"] = result_transcripts[0][0]
H
huangyuxin 已提交
300 301 302
        else:
            raise Exception("invalid model name")

K
KP 已提交
303 304 305 306
    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._outputs["result"]
K
KP 已提交
308

H
huangyuxin 已提交
309 310 311
    def _check(self, audio_file: str, sample_rate: int):
        self.sample_rate = sample_rate
        if self.sample_rate != 16000 and self.sample_rate != 8000:
H
huangyuxin 已提交
312
            logger.error(
H
huangyuxin 已提交
313
                "please input --sr 8000 or --sr 16000"
H
huangyuxin 已提交
314
            )
H
huangyuxin 已提交
315 316 317 318 319 320 321 322 323
            raise Exception("invalid sample rate")
            sys.exit(-1)

        if not os.path.isfile(audio_file):
            logger.error("Please input the right audio file path")
            sys.exit(-1)

        logger.info("checking the audio file format......")
        try:
H
huangyuxin 已提交
324
            audio, audio_sample_rate = soundfile.read(
H
huangyuxin 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337
                audio_file, dtype="int16", always_2d=True)
        except Exception as e:
            logger.error(str(e))
            logger.error(
                "can not open the audio file, please check the audio file format is 'wav'. \n \
                 you can try to use sox to change the file format.\n \
                 For example: \n \
                 sample rate: 16k \n \
                 sox input_audio.xx --rate 16k --bits 16 --channels 1 output_audio.wav \n \
                 sample rate: 8k \n \
                 sox input_audio.xx --rate 8k --bits 16 --channels 1 output_audio.wav \n \
                 ")
            sys.exit(-1)
H
huangyuxin 已提交
338 339
        logger.info("The sample rate is %d" % audio_sample_rate)
        if audio_sample_rate != self.sample_rate:
H
huangyuxin 已提交
340 341
            logger.warning(
                "The sample rate of the input file is not {}.\n \
H
huangyuxin 已提交
342 343 344
                            The program will resample the wav file to {}.\n \
                            If the result does not meet your expectations,\n \
                            Please input the 16k 16bit 1 channel wav file. \
H
huangyuxin 已提交
345
                        "
H
huangyuxin 已提交
346
                .format(self.sample_rate, self.sample_rate))
H
huangyuxin 已提交
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
            while (True):
                logger.info(
                    "Whether to change the sample rate and the channel. Y: change the sample. N: exit the prgream."
                )
                content = input("Input(Y/N):")
                if content.strip() == "Y" or content.strip(
                ) == "y" or content.strip() == "yes" or content.strip() == "Yes":
                    logger.info(
                        "change the sampele rate, channel to 16k and 1 channel")
                    break
                elif content.strip() == "N" or content.strip(
                ) == "n" or content.strip() == "no" or content.strip() == "No":
                    logger.info("Exit the program")
                    exit(1)
                else:
                    logger.warning("Not regular input, please input again")

            self.change_format = True
        else:
            logger.info("The audio file format is right")
            self.change_format = False

K
KP 已提交
369
    def execute(self, argv: List[str]) -> bool:
K
KP 已提交
370 371 372
        """
            Command line entry.
        """
H
huangyuxin 已提交
373
        parser_args = self.parser.parse_args(argv)
K
KP 已提交
374

H
huangyuxin 已提交
375 376
        model = parser_args.model
        lang = parser_args.lang
H
huangyuxin 已提交
377
        sample_rate = parser_args.sr
H
huangyuxin 已提交
378 379 380 381
        config = parser_args.config
        ckpt_path = parser_args.ckpt_path
        audio_file = parser_args.input
        device = parser_args.device
K
KP 已提交
382 383

        try:
H
huangyuxin 已提交
384
            res = self(model, lang, sample_rate, config, ckpt_path,
H
huangyuxin 已提交
385
                       audio_file, device)
K
KP 已提交
386
            logger.info('ASR Result: {}'.format(res))
K
KP 已提交
387 388 389 390
            return True
        except Exception as e:
            print(e)
            return False
H
huangyuxin 已提交
391

H
huangyuxin 已提交
392
    def __call__(self, model, lang, sample_rate, config, ckpt_path,
H
huangyuxin 已提交
393
                 audio_file, device):
K
KP 已提交
394 395 396
        """
            Python API to call an executor.
        """
H
huangyuxin 已提交
397
        audio_file = os.path.abspath(audio_file)
H
huangyuxin 已提交
398
        self._check(audio_file, sample_rate)
K
KP 已提交
399
        paddle.set_device(device)
H
revise  
huangyuxin 已提交
400
        self._init_from_path(model, lang, sample_rate, config, ckpt_path)
H
huangyuxin 已提交
401 402
        self.preprocess(model, audio_file)
        self.infer(model)
K
KP 已提交
403
        res = self.postprocess()  # Retrieve result of asr.
H
huangyuxin 已提交
404

K
KP 已提交
405
        return res