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

import paddle

from ..executor import BaseExecutor
from ..utils import cli_register
K
KP 已提交
24 25 26
from ..utils import download_and_decompress
from ..utils import logger
from ..utils import MODEL_HOME
K
KP 已提交
27 28 29

__all__ = ['S2TExecutor']

K
KP 已提交
30 31 32 33 34 35 36 37 38
pretrained_models = {
    "wenetspeech_zh": {
        'url':
        'https://paddlespeech.bj.bcebos.com/s2t/wenetspeech/conformer.model.tar.gz',
        'md5':
        '54e7a558a6e020c2f5fb224874943f97',
    }
}

K
KP 已提交
39

K
KP 已提交
40 41
@cli_register(
    name='paddlespeech.s2t', description='Speech to text infer command.')
K
KP 已提交
42 43 44 45 46 47
class S2TExecutor(BaseExecutor):
    def __init__(self):
        super(S2TExecutor, self).__init__()

        self.parser = argparse.ArgumentParser(
            prog='paddlespeech.s2t', add_help=True)
K
KP 已提交
48 49 50 51 52 53 54
        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 已提交
55 56 57 58 59
        self.parser.add_argument(
            '--config',
            type=str,
            default=None,
            help='Config of s2t task. Use deault config when it is None.')
K
KP 已提交
60 61 62 63 64
        self.parser.add_argument(
            '--ckpt_path',
            type=str,
            default=None,
            help='Checkpoint file of model.')
K
KP 已提交
65 66 67 68 69 70 71 72
        self.parser.add_argument(
            '--input', type=str, help='Audio file to recognize.')
        self.parser.add_argument(
            '--device',
            type=str,
            default='cpu',
            help='Choose device to execute model inference.')

K
KP 已提交
73
    def _get_pretrained_path(self, tag: str) -> os.PathLike:
K
KP 已提交
74
        """
K
KP 已提交
75
            Download and returns pretrained resources path of current task.
K
KP 已提交
76
        """
K
KP 已提交
77 78 79 80 81 82 83 84 85
        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)
        logger.info(
            'Use pretrained model stored in: {}'.format(decompressed_path))
        return decompressed_path
K
KP 已提交
86

K
KP 已提交
87 88 89 90 91
    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 已提交
92
        """
K
KP 已提交
93
            Init model and other resources from a specific path.
K
KP 已提交
94
        """
K
KP 已提交
95 96 97 98 99 100 101 102 103 104 105
        if cfg_path is None or ckpt_path is None:
            res_path = self._get_pretrained_path(
                model_type + '_' + lang)  # wenetspeech_zh
            cfg_path = os.path.join(res_path, 'conf/conformer.yaml')
            ckpt_path = os.path.join(
                res_path, 'exp/conformer/checkpoints/wenetspeech.pdparams')
            logger.info(res_path)
            logger.info(cfg_path)
            logger.info(ckpt_path)

        # Init body.
K
KP 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
        pass

    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).
        """
        pass

    @paddle.no_grad()
    def infer(self):
        """
            Model inference and result stored in self.output.
        """
        pass

    def postprocess(self) -> Union[str, os.PathLike]:
        """
            Output postprocess and return human-readable results such as texts and audio files.
        """
        pass

    def execute(self, argv: List[str]) -> bool:
K
KP 已提交
129 130 131
        """
            Command line entry.
        """
K
KP 已提交
132 133 134
        parser_args = self.parser.parse_args(argv)
        print(parser_args)

K
KP 已提交
135 136
        model = parser_args.model
        lang = parser_args.lang
K
KP 已提交
137
        config = parser_args.config
K
KP 已提交
138
        ckpt_path = parser_args.ckpt_path
K
KP 已提交
139 140 141 142
        audio_file = parser_args.input
        device = parser_args.device

        try:
K
KP 已提交
143
            res = self(model, lang, config, ckpt_path, audio_file, device)
K
KP 已提交
144 145 146 147 148
            print(res)
            return True
        except Exception as e:
            print(e)
            return False
K
KP 已提交
149 150 151 152 153 154 155 156 157 158 159

    def __call__(self, model, lang, config, ckpt_path, audio_file, device):
        """
            Python API to call an executor.
        """
        self._init_from_path(model, lang, config, ckpt_path)
        self.preprocess(audio_file)
        self.infer()
        res = self.postprocess()  # Retrieve result of s2t.

        return res