asr_engine.py 3.8 KB
Newer Older
W
WilliamZhang06 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
# Copyright (c) 2022 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.
W
WilliamZhang06 已提交
14
import io
L
lym0302 已提交
15
import sys
L
lym0302 已提交
16
import time
W
WilliamZhang06 已提交
17

18 19
import paddle

W
WilliamZhang06 已提交
20
from paddlespeech.cli.asr.infer import ASRExecutor
21
from paddlespeech.cli.log import logger
L
lym0302 已提交
22
from paddlespeech.server.engine.base_engine import BaseEngine
W
WilliamZhang06 已提交
23

L
lym0302 已提交
24
__all__ = ['ASREngine', 'PaddleASRConnectionHandler']
W
WilliamZhang06 已提交
25 26


W
WilliamZhang06 已提交
27 28 29 30 31 32
class ASRServerExecutor(ASRExecutor):
    def __init__(self):
        super().__init__()
        pass


33
class ASREngine(BaseEngine):
W
WilliamZhang06 已提交
34 35 36 37 38
    """ASR server engine

    Args:
        metaclass: Defaults to Singleton.
    """
39

40
    def __init__(self):
W
WilliamZhang06 已提交
41
        super(ASREngine, self).__init__()
42

L
lym0302 已提交
43
    def init(self, config: dict) -> bool:
44 45 46 47
        """init engine resource

        Args:
            config_file (str): config file
W
WilliamZhang06 已提交
48

49 50 51
        Returns:
            bool: init failed or success
        """
W
WilliamZhang06 已提交
52
        self.executor = ASRServerExecutor()
L
lym0302 已提交
53
        self.config = config
L
lym0302 已提交
54 55
        self.engine_type = "python"

L
lym0302 已提交
56
        try:
L
lym0302 已提交
57
            if self.config.device is not None:
L
lym0302 已提交
58 59 60
                self.device = self.config.device
            else:
                self.device = paddle.get_device()
L
lym0302 已提交
61

L
lym0302 已提交
62
            paddle.set_device(self.device)
L
lym0302 已提交
63
        except Exception as e:
L
lym0302 已提交
64 65 66
            logger.error(
                "Set device failed, please check if device is already used and the parameter 'device' in the yaml file"
            )
L
lym0302 已提交
67 68
            logger.error(e)
            return False
L
lym0302 已提交
69

70 71 72 73
        self.executor._init_from_path(
            self.config.model, self.config.lang, self.config.sample_rate,
            self.config.cfg_path, self.config.decode_method,
            self.config.ckpt_path)
W
WilliamZhang06 已提交
74

L
lym0302 已提交
75 76
        logger.info("Initialize ASR server engine successfully on device: %s." %
                    (self.device))
77
        return True
W
WilliamZhang06 已提交
78

L
lym0302 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

class PaddleASRConnectionHandler(ASRServerExecutor):
    def __init__(self, asr_engine):
        """The PaddleSpeech ASR Server Connection Handler
           This connection process every asr server request
        Args:
            asr_engine (ASREngine): The ASR engine
        """
        super().__init__()
        self.input = None
        self.output = None
        self.asr_engine = asr_engine
        self.executor = self.asr_engine.executor
        self.max_len = self.executor.max_len
        self.text_feature = self.executor.text_feature
        self.model = self.executor.model
        self.config = self.executor.config

W
WilliamZhang06 已提交
97
    def run(self, audio_data):
98
        """engine run 
W
WilliamZhang06 已提交
99

100 101 102
        Args:
            audio_data (bytes): base64.b64decode
        """
103
        try:
L
lym0302 已提交
104 105 106
            if self._check(
                    io.BytesIO(audio_data), self.asr_engine.config.sample_rate,
                    self.asr_engine.config.force_yes):
107
                logger.info("start run asr engine")
L
lym0302 已提交
108 109
                self.preprocess(self.asr_engine.config.model,
                                io.BytesIO(audio_data))
110
                st = time.time()
L
lym0302 已提交
111
                self.infer(self.asr_engine.config.model)
112
                infer_time = time.time() - st
L
lym0302 已提交
113
                self.output = self.postprocess()  # Retrieve result of asr.
114 115 116 117 118 119 120 121
            else:
                logger.info("file check failed!")
                self.output = None

            logger.info("inference time: {}".format(infer_time))
            logger.info("asr engine type: python")
        except Exception as e:
            logger.info(e)
L
lym0302 已提交
122
            sys.exit(-1)