infer.py 13.2 KB
Newer Older
G
gongel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# 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
import subprocess
from typing import List
from typing import Optional
from typing import Union

G
gongel 已提交
21
import kaldiio
G
gongel 已提交
22 23
import numpy as np
import paddle
24
import soundfile
G
gongel 已提交
25 26 27 28
from kaldiio import WriteHelper
from yacs.config import CfgNode

from ..executor import BaseExecutor
K
KP 已提交
29
from ..log import logger
G
gongel 已提交
30 31 32
from ..utils import cli_register
from ..utils import download_and_decompress
from ..utils import MODEL_HOME
K
KP 已提交
33
from ..utils import stats_wrapper
G
format  
gongel 已提交
34 35 36
from paddlespeech.s2t.frontend.featurizer.text_featurizer import TextFeaturizer
from paddlespeech.s2t.utils.dynamic_import import dynamic_import
from paddlespeech.s2t.utils.utility import UpdateConfig
G
gongel 已提交
37 38 39 40

__all__ = ["STExecutor"]

pretrained_models = {
K
KP 已提交
41
    "fat_st_ted-en-zh": {
G
gongel 已提交
42
        "url":
H
huangyuxin 已提交
43
        "https://paddlespeech.bj.bcebos.com/s2t/ted_en_zh/st1/st1_transformer_mtl_noam_ted-en-zh_ckpt_0.1.1.model.tar.gz",
G
gongel 已提交
44
        "md5":
H
huangyuxin 已提交
45
        "d62063f35a16d91210a71081bd2dd557",
G
gongel 已提交
46
        "cfg_path":
H
huangyuxin 已提交
47
        "model.yaml",
G
gongel 已提交
48
        "ckpt_path":
49
        "exp/transformer_mtl_noam/checkpoints/fat_st_ted-en-zh.pdparams",
G
gongel 已提交
50 51 52
    }
}

K
KP 已提交
53
model_alias = {"fat_st": "paddlespeech.s2t.models.u2_st:U2STModel"}
G
gongel 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

kaldi_bins = {
    "url":
    "https://paddlespeech.bj.bcebos.com/s2t/ted_en_zh/st1/kaldi_bins.tar.gz",
    "md5":
    "c0682303b3f3393dbf6ed4c4e35a53eb",
}


@cli_register(
    name="paddlespeech.st", description="Speech translation infer command.")
class STExecutor(BaseExecutor):
    def __init__(self):
        super(STExecutor, self).__init__()

        self.parser = argparse.ArgumentParser(
            prog="paddlespeech.st", add_help=True)
        self.parser.add_argument(
            "--input", type=str, required=True, help="Audio file to translate.")
        self.parser.add_argument(
K
KP 已提交
74
            "--model",
G
gongel 已提交
75
            type=str,
76
            default="fat_st_ted",
K
KP 已提交
77
            choices=[tag[:tag.index('-')] for tag in pretrained_models.keys()],
G
gongel 已提交
78 79
            help="Choose model type of st task.")
        self.parser.add_argument(
80
            "--src_lang",
G
gongel 已提交
81
            type=str,
82 83
            default="en",
            help="Choose model source language.")
G
gongel 已提交
84
        self.parser.add_argument(
85 86 87 88 89 90 91 92 93 94 95
            "--tgt_lang",
            type=str,
            default="zh",
            help="Choose model target language.")
        self.parser.add_argument(
            "--sample_rate",
            type=int,
            default=16000,
            choices=[16000],
            help='Choose the audio sample rate of the model. 8000 or 16000')
        self.parser.add_argument(
K
KP 已提交
96
            "--config",
G
gongel 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
            type=str,
            default=None,
            help="Config of st task. Use deault config when it is None.")
        self.parser.add_argument(
            "--ckpt_path",
            type=str,
            default=None,
            help="Checkpoint file of model.")
        self.parser.add_argument(
            "--device",
            type=str,
            default=paddle.get_device(),
            help="Choose device to execute model inference.")

    def _get_pretrained_path(self, tag: str) -> os.PathLike:
        """
            Download and returns pretrained resources path of current task.
        """
        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)
        decompressed_path = os.path.abspath(decompressed_path)
        logger.info(
            "Use pretrained model stored in: {}".format(decompressed_path))

        return decompressed_path

    def _set_kaldi_bins(self) -> os.PathLike:
        """
            Download and returns kaldi_bins resources path of current task.
        """
        decompressed_path = download_and_decompress(kaldi_bins, MODEL_HOME)
        decompressed_path = os.path.abspath(decompressed_path)
        logger.info("Kaldi_bins stored in: {}".format(decompressed_path))
134 135 136 137
        if "LD_LIBRARY_PATH" in os.environ:
            os.environ["LD_LIBRARY_PATH"] += f":{decompressed_path}"
        else:
            os.environ["LD_LIBRARY_PATH"] = f"{decompressed_path}"
G
gongel 已提交
138 139 140 141
        os.environ["PATH"] += f":{decompressed_path}"
        return decompressed_path

    def _init_from_path(self,
142 143 144
                        model_type: str="fat_st_ted",
                        src_lang: str="en",
                        tgt_lang: str="zh",
G
gongel 已提交
145 146 147 148 149
                        cfg_path: Optional[os.PathLike]=None,
                        ckpt_path: Optional[os.PathLike]=None):
        """
            Init model and other resources from a specific path.
        """
150 151 152 153
        if hasattr(self, 'model'):
            logger.info('Model had been initialized.')
            return

G
gongel 已提交
154
        if cfg_path is None or ckpt_path is None:
K
KP 已提交
155
            tag = model_type + "-" + src_lang + "-" + tgt_lang
G
gongel 已提交
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
            res_path = self._get_pretrained_path(tag)
            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"])
            logger.info(res_path)
            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)))

        #Init body.
        self.config = CfgNode(new_allowed=True)
        self.config.merge_from_file(self.cfg_path)
H
huangyuxin 已提交
173
        self.config.decode.decoding_method = "fullsentence"
G
gongel 已提交
174 175

        with UpdateConfig(self.config):
H
huangyuxin 已提交
176 177 178 179
            self.config.cmvn_path = os.path.join(
                res_path, self.config.cmvn_path)
            self.config.spm_model_prefix = os.path.join(
                res_path, self.config.spm_model_prefix)
G
gongel 已提交
180
            self.text_feature = TextFeaturizer(
H
huangyuxin 已提交
181 182 183
                unit_type=self.config.unit_type,
                vocab=self.config.vocab_filepath,
                spm_model_prefix=self.config.spm_model_prefix)
G
gongel 已提交
184

H
huangyuxin 已提交
185
        model_conf = self.config
K
KP 已提交
186 187 188
        model_name = model_type[:model_type.rindex(
            '_')]  # model_type: {model_name}_{dataset}
        model_class = dynamic_import(model_name, model_alias)
G
gongel 已提交
189 190 191 192
        self.model = model_class.from_config(model_conf)
        self.model.eval()

        # load model
193
        params_path = self.ckpt_path
G
gongel 已提交
194 195 196 197 198 199
        model_dict = paddle.load(params_path)
        self.model.set_state_dict(model_dict)

        # set kaldi bins
        self._set_kaldi_bins()

200 201 202 203 204 205 206
    def _check(self, audio_file: str, sample_rate: int):
        _, audio_sample_rate = soundfile.read(
            audio_file, dtype="int16", always_2d=True)
        if audio_sample_rate != sample_rate:
            raise Exception("invalid sample rate")
            sys.exit(-1)

G
gongel 已提交
207 208 209 210 211 212 213 214
    def preprocess(self, wav_file: Union[str, os.PathLike], model_type: str):
        """
            Input preprocess and return paddle.Tensor stored in self.input.
            Input content can be a file(wav).
        """
        audio_file = os.path.abspath(wav_file)
        logger.info("Preprocess audio_file:" + audio_file)

K
KP 已提交
215
        if "fat_st" in model_type:
H
huangyuxin 已提交
216
            cmvn = self.config.cmvn_path
G
gongel 已提交
217 218 219 220 221 222 223 224 225 226
            utt_name = "_tmp"

            # Get the object for feature extraction
            fbank_extract_command = [
                "compute-fbank-feats", "--num-mel-bins=80", "--verbose=2",
                "--sample-frequency=16000", "scp:-", "ark:-"
            ]
            fbank_extract_process = subprocess.Popen(
                fbank_extract_command,
                stdin=subprocess.PIPE,
227 228
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)
G
gongel 已提交
229 230 231 232
            fbank_extract_process.stdin.write(
                f"{utt_name} {wav_file}".encode("utf8"))
            fbank_extract_process.stdin.close()
            fbank_feat = dict(
G
gongel 已提交
233
                kaldiio.load_ark(fbank_extract_process.stdout))[utt_name]
G
gongel 已提交
234 235 236

            extract_command = ["compute-kaldi-pitch-feats", "scp:-", "ark:-"]
            pitch_extract_process = subprocess.Popen(
237 238 239 240
                extract_command,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)
G
gongel 已提交
241 242 243 244 245 246
            pitch_extract_process.stdin.write(
                f"{utt_name} {wav_file}".encode("utf8"))
            process_command = ["process-kaldi-pitch-feats", "ark:", "ark:-"]
            pitch_process = subprocess.Popen(
                process_command,
                stdin=pitch_extract_process.stdout,
247 248
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)
G
gongel 已提交
249
            pitch_extract_process.stdin.close()
G
gongel 已提交
250
            pitch_feat = dict(kaldiio.load_ark(pitch_process.stdout))[utt_name]
G
gongel 已提交
251 252 253 254 255 256 257 258 259 260
            concated_feat = np.concatenate((fbank_feat, pitch_feat), axis=1)
            raw_feat = f"{utt_name}.raw"
            with WriteHelper(
                    f"ark,scp:{raw_feat}.ark,{raw_feat}.scp") as writer:
                writer(utt_name, concated_feat)
            cmvn_command = [
                "apply-cmvn", "--norm-vars=true", cmvn, f"scp:{raw_feat}.scp",
                "ark:-"
            ]
            cmvn_process = subprocess.Popen(
261
                cmvn_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
G
gongel 已提交
262 263 264 265 266 267
            process_command = [
                "copy-feats", "--compress=true", "ark:-", "ark:-"
            ]
            process = subprocess.Popen(
                process_command,
                stdin=cmvn_process.stdout,
268 269
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)
G
gongel 已提交
270
            norm_feat = dict(kaldiio.load_ark(process.stdout))[utt_name]
271 272 273
            self._inputs["audio"] = paddle.to_tensor(norm_feat).unsqueeze(0)
            self._inputs["audio_len"] = paddle.to_tensor(
                self._inputs["audio"].shape[1], dtype="int64")
G
gongel 已提交
274 275 276 277 278 279 280 281
        else:
            raise ValueError("Wrong model type.")

    @paddle.no_grad()
    def infer(self, model_type: str):
        """
            Model inference and result stored in self.output.
        """
H
huangyuxin 已提交
282
        cfg = self.config.decode
283 284 285
        audio = self._inputs["audio"]
        audio_len = self._inputs["audio_len"]
        if model_type == "fat_st_ted":
G
gongel 已提交
286 287 288 289 290 291 292 293 294 295
            hyps = self.model.decode(
                audio,
                audio_len,
                text_feature=self.text_feature,
                decoding_method=cfg.decoding_method,
                beam_size=cfg.beam_size,
                word_reward=cfg.word_reward,
                decoding_chunk_size=cfg.decoding_chunk_size,
                num_decoding_left_chunks=cfg.num_decoding_left_chunks,
                simulate_streaming=cfg.simulate_streaming)
296
            self._outputs["result"] = hyps
G
gongel 已提交
297 298 299 300 301 302 303
        else:
            raise ValueError("Wrong model type.")

    def postprocess(self, model_type: str) -> Union[str, os.PathLike]:
        """
            Output postprocess and return human-readable results such as texts and audio files.
        """
304 305
        if model_type == "fat_st_ted":
            return self._outputs["result"]
G
gongel 已提交
306 307 308 309 310 311 312 313 314
        else:
            raise ValueError("Wrong model type.")

    def execute(self, argv: List[str]) -> bool:
        """
            Command line entry.
        """
        parser_args = self.parser.parse_args(argv)

K
KP 已提交
315
        model = parser_args.model
316 317 318
        src_lang = parser_args.src_lang
        tgt_lang = parser_args.tgt_lang
        sample_rate = parser_args.sample_rate
K
KP 已提交
319
        config = parser_args.config
G
gongel 已提交
320 321 322 323 324
        ckpt_path = parser_args.ckpt_path
        audio_file = parser_args.input
        device = parser_args.device

        try:
K
KP 已提交
325 326
            res = self(audio_file, model, src_lang, tgt_lang, sample_rate,
                       config, ckpt_path, device)
327
            logger.info("ST Result: {}".format(res))
G
gongel 已提交
328 329
            return True
        except Exception as e:
K
KP 已提交
330
            logger.exception(e)
G
gongel 已提交
331 332
            return False

K
KP 已提交
333
    @stats_wrapper
K
KP 已提交
334 335 336 337 338 339 340 341 342
    def __call__(self,
                 audio_file: os.PathLike,
                 model: str='fat_st_ted',
                 src_lang: str='en',
                 tgt_lang: str='zh',
                 sample_rate: int=16000,
                 config: Optional[os.PathLike]=None,
                 ckpt_path: Optional[os.PathLike]=None,
                 device: str=paddle.get_device()):
G
gongel 已提交
343 344 345 346
        """
            Python API to call an executor.
        """
        audio_file = os.path.abspath(audio_file)
347
        self._check(audio_file, sample_rate)
G
gongel 已提交
348
        paddle.set_device(device)
K
KP 已提交
349 350 351 352
        self._init_from_path(model, src_lang, tgt_lang, config, ckpt_path)
        self.preprocess(audio_file, model)
        self.infer(model)
        res = self.postprocess(model)
G
gongel 已提交
353 354

        return res