infer.py 16.6 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
H
revise  
huangyuxin 已提交
25
import numpy as np
K
KP 已提交
26 27 28

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

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

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

H
huangyuxin 已提交
52 53 54 55 56 57 58 59
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 已提交
60

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

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

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

K
KP 已提交
117
        return decompressed_path
K
KP 已提交
118

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

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

        model_class = dynamic_import(model_type, model_alias)
H
huangyuxin 已提交
183 184 185 186 187
        model = model_class.from_config(model_conf)
        self.model = model
        self.model.eval()

        # load model
H
revise  
huangyuxin 已提交
188
        model_dict = paddle.load(self.ckpt_path)
H
huangyuxin 已提交
189
        self.model.set_state_dict(model_dict)
K
KP 已提交
190

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

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

        # Get the object for feature extraction
H
huangyuxin 已提交
201
        if model_type == "ds2_online" or model_type == "ds2_offline":
H
huangyuxin 已提交
202
            audio, _ = self.collate_fn_test.process_utterance(
H
huangyuxin 已提交
203 204 205
                audio_file=audio_file, transcript=" ")
            audio_len = audio.shape[0]
            audio = paddle.to_tensor(audio, dtype='float32')
H
huangyuxin 已提交
206 207 208 209 210 211 212 213
            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 已提交
214 215 216 217 218 219 220 221
            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 已提交
222
            logger.info("read the audio file")
H
huangyuxin 已提交
223
            audio, audio_sample_rate = soundfile.read(
H
huangyuxin 已提交
224
                audio_file, dtype="int16", always_2d=True)
H
huangyuxin 已提交
225 226 227 228 229 230

            if self.change_format:
                if audio.shape[1] >= 2:
                    audio = audio.mean(axis=1)
                else:
                    audio = audio[:, 0]
H
revise  
huangyuxin 已提交
231
                # pcm16 -> pcm 32
H
huangyuxin 已提交
232
                audio = audio.astype("float32")
H
revise  
huangyuxin 已提交
233 234
                bits = np.iinfo(np.int16).bits
                audio = audio / (2**(bits - 1))
H
huangyuxin 已提交
235 236 237
                audio = librosa.resample(audio, audio_sample_rate,
                                         self.sample_rate)
                audio_sample_rate = self.sample_rate
H
revise  
huangyuxin 已提交
238 239 240
                # pcm16 -> pcm 32
                audio = audio * (2**(bits - 1))
                audio = np.round(audio).astype("int16")
H
huangyuxin 已提交
241 242 243
            else:
                audio = audio[:, 0]

H
huangyuxin 已提交
244 245 246 247
            logger.info(f"audio shape: {audio.shape}")
            # fbank
            audio = preprocessing(audio, **preprocess_args)

H
huangyuxin 已提交
248 249 250 251 252 253 254 255 256
            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 已提交
257 258 259

        else:
            raise Exception("wrong type")
K
KP 已提交
260 261

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

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

K
KP 已提交
309 310 311 312
    def postprocess(self) -> Union[str, os.PathLike]:
        """
            Output postprocess and return human-readable results such as texts and audio files.
        """
H
huangyuxin 已提交
313
        return self._outputs["result"]
K
KP 已提交
314

H
huangyuxin 已提交
315 316 317
    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 已提交
318
            logger.error(
H
huangyuxin 已提交
319
                "please input --sr 8000 or --sr 16000"
H
huangyuxin 已提交
320
            )
H
huangyuxin 已提交
321 322 323 324 325 326 327 328 329
            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 已提交
330
            audio, audio_sample_rate = soundfile.read(
H
huangyuxin 已提交
331 332 333 334 335 336 337 338 339 340 341 342 343
                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 已提交
344 345
        logger.info("The sample rate is %d" % audio_sample_rate)
        if audio_sample_rate != self.sample_rate:
H
huangyuxin 已提交
346 347
            logger.warning(
                "The sample rate of the input file is not {}.\n \
H
huangyuxin 已提交
348 349
                            The program will resample the wav file to {}.\n \
                            If the result does not meet your expectations,\n \
H
revise  
huangyuxin 已提交
350
                            Please input the 16k 16 bit 1 channel wav file. \
H
huangyuxin 已提交
351
                        "
H
huangyuxin 已提交
352
                .format(self.sample_rate, self.sample_rate))
H
huangyuxin 已提交
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
            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 已提交
375
    def execute(self, argv: List[str]) -> bool:
K
KP 已提交
376 377 378
        """
            Command line entry.
        """
H
huangyuxin 已提交
379
        parser_args = self.parser.parse_args(argv)
K
KP 已提交
380

H
huangyuxin 已提交
381 382
        model = parser_args.model
        lang = parser_args.lang
H
huangyuxin 已提交
383
        sample_rate = parser_args.sr
H
huangyuxin 已提交
384 385 386 387
        config = parser_args.config
        ckpt_path = parser_args.ckpt_path
        audio_file = parser_args.input
        device = parser_args.device
K
KP 已提交
388 389

        try:
H
huangyuxin 已提交
390
            res = self(model, lang, sample_rate, config, ckpt_path,
H
huangyuxin 已提交
391
                       audio_file, device)
K
KP 已提交
392
            logger.info('ASR Result: {}'.format(res))
K
KP 已提交
393 394 395 396
            return True
        except Exception as e:
            print(e)
            return False
H
huangyuxin 已提交
397

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

K
KP 已提交
411
        return res