|
11 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 | 12 | # See the License for the specific language governing permissions and
|
13 | 13 | # limitations under the License.
|
| 14 | +import io |
| 15 | +import os |
| 16 | +from typing import List |
| 17 | +from typing import Optional |
| 18 | +from typing import Union |
| 19 | + |
| 20 | +import librosa |
| 21 | +import paddle |
| 22 | +import soundfile |
14 | 23 | from engine.base_engine import BaseEngine
|
15 | 24 |
|
16 |
| -from utils.log import logger |
| 25 | +from paddlespeech.cli.asr.infer import ASRExecutor |
| 26 | +from paddlespeech.cli.log import logger |
| 27 | +from paddlespeech.s2t.frontend.featurizer.text_featurizer import TextFeaturizer |
| 28 | +from paddlespeech.s2t.transform.transformation import Transformation |
| 29 | +from paddlespeech.s2t.utils.dynamic_import import dynamic_import |
| 30 | +from paddlespeech.s2t.utils.utility import UpdateConfig |
17 | 31 | from utils.config import get_config
|
18 | 32 |
|
19 | 33 | __all__ = ['ASREngine']
|
20 | 34 |
|
21 | 35 |
|
| 36 | +class ASRServerExecutor(ASRExecutor): |
| 37 | + def __init__(self): |
| 38 | + super().__init__() |
| 39 | + pass |
| 40 | + |
| 41 | + def _check(self, audio_file: str, sample_rate: int, force_yes: bool): |
| 42 | + self.sample_rate = sample_rate |
| 43 | + if self.sample_rate != 16000 and self.sample_rate != 8000: |
| 44 | + logger.error("please input --sr 8000 or --sr 16000") |
| 45 | + return False |
| 46 | + |
| 47 | + logger.info("checking the audio file format......") |
| 48 | + try: |
| 49 | + audio, audio_sample_rate = soundfile.read( |
| 50 | + audio_file, dtype="int16", always_2d=True) |
| 51 | + except Exception as e: |
| 52 | + logger.exception(e) |
| 53 | + logger.error( |
| 54 | + "can not open the audio file, please check the audio file format is 'wav'. \n \ |
| 55 | + you can try to use sox to change the file format.\n \ |
| 56 | + For example: \n \ |
| 57 | + sample rate: 16k \n \ |
| 58 | + sox input_audio.xx --rate 16k --bits 16 --channels 1 output_audio.wav \n \ |
| 59 | + sample rate: 8k \n \ |
| 60 | + sox input_audio.xx --rate 8k --bits 16 --channels 1 output_audio.wav \n \ |
| 61 | + ") |
| 62 | + |
| 63 | + logger.info("The sample rate is %d" % audio_sample_rate) |
| 64 | + if audio_sample_rate != self.sample_rate: |
| 65 | + logger.warning("The sample rate of the input file is not {}.\n \ |
| 66 | + The program will resample the wav file to {}.\n \ |
| 67 | + If the result does not meet your expectations,\n \ |
| 68 | + Please input the 16k 16 bit 1 channel wav file. \ |
| 69 | + ".format(self.sample_rate, self.sample_rate)) |
| 70 | + self.change_format = True |
| 71 | + else: |
| 72 | + logger.info("The audio file format is right") |
| 73 | + self.change_format = False |
| 74 | + |
| 75 | + return True |
| 76 | + |
| 77 | + def preprocess(self, model_type: str, input: Union[str, os.PathLike]): |
| 78 | + """ |
| 79 | + Input preprocess and return paddle.Tensor stored in self.input. |
| 80 | + Input content can be a text(tts), a file(asr, cls) or a streaming(not supported yet). |
| 81 | + """ |
| 82 | + |
| 83 | + audio_file = input |
| 84 | + |
| 85 | + # Get the object for feature extraction |
| 86 | + if "deepspeech2online" in model_type or "deepspeech2offline" in model_type: |
| 87 | + audio, _ = self.collate_fn_test.process_utterance( |
| 88 | + audio_file=audio_file, transcript=" ") |
| 89 | + audio_len = audio.shape[0] |
| 90 | + audio = paddle.to_tensor(audio, dtype='float32') |
| 91 | + audio_len = paddle.to_tensor(audio_len) |
| 92 | + audio = paddle.unsqueeze(audio, axis=0) |
| 93 | + # vocab_list = collate_fn_test.vocab_list |
| 94 | + self._inputs["audio"] = audio |
| 95 | + self._inputs["audio_len"] = audio_len |
| 96 | + logger.info(f"audio feat shape: {audio.shape}") |
| 97 | + |
| 98 | + elif "conformer" in model_type or "transformer" in model_type or "wenetspeech" in model_type: |
| 99 | + logger.info("get the preprocess conf") |
| 100 | + preprocess_conf = self.config.preprocess_config |
| 101 | + preprocess_args = {"train": False} |
| 102 | + preprocessing = Transformation(preprocess_conf) |
| 103 | + logger.info("read the audio file") |
| 104 | + audio, audio_sample_rate = soundfile.read( |
| 105 | + audio_file, dtype="int16", always_2d=True) |
| 106 | + |
| 107 | + if self.change_format: |
| 108 | + if audio.shape[1] >= 2: |
| 109 | + audio = audio.mean(axis=1, dtype=np.int16) |
| 110 | + else: |
| 111 | + audio = audio[:, 0] |
| 112 | + # pcm16 -> pcm 32 |
| 113 | + audio = self._pcm16to32(audio) |
| 114 | + audio = librosa.resample(audio, audio_sample_rate, |
| 115 | + self.sample_rate) |
| 116 | + audio_sample_rate = self.sample_rate |
| 117 | + # pcm32 -> pcm 16 |
| 118 | + audio = self._pcm32to16(audio) |
| 119 | + else: |
| 120 | + audio = audio[:, 0] |
| 121 | + |
| 122 | + logger.info(f"audio shape: {audio.shape}") |
| 123 | + # fbank |
| 124 | + audio = preprocessing(audio, **preprocess_args) |
| 125 | + |
| 126 | + audio_len = paddle.to_tensor(audio.shape[0]) |
| 127 | + audio = paddle.to_tensor(audio, dtype='float32').unsqueeze(axis=0) |
| 128 | + |
| 129 | + self._inputs["audio"] = audio |
| 130 | + self._inputs["audio_len"] = audio_len |
| 131 | + logger.info(f"audio feat shape: {audio.shape}") |
| 132 | + |
| 133 | + else: |
| 134 | + raise Exception("wrong type") |
| 135 | + |
| 136 | + |
22 | 137 | class ASREngine(BaseEngine):
|
| 138 | + """ASR server engine |
| 139 | +
|
| 140 | + Args: |
| 141 | + metaclass: Defaults to Singleton. |
| 142 | + """ |
| 143 | + |
23 | 144 | def __init__(self):
|
24 | 145 | super(ASREngine, self).__init__()
|
25 | 146 |
|
26 |
| - def init(self, config_file: str): |
27 |
| - self.config_file = config_file |
28 |
| - self.executor = None |
| 147 | + def init(self, config_file: str) -> bool: |
| 148 | + """init engine resource |
| 149 | +
|
| 150 | + Args: |
| 151 | + config_file (str): config file |
| 152 | +
|
| 153 | + Returns: |
| 154 | + bool: init failed or success |
| 155 | + """ |
29 | 156 | self.input = None
|
30 | 157 | self.output = None
|
31 |
| - config = get_config(self.config_file) |
32 |
| - pass |
| 158 | + self.executor = ASRServerExecutor() |
33 | 159 |
|
34 |
| - def postprocess(self): |
35 |
| - pass |
| 160 | + try: |
| 161 | + self.config = get_config(config_file) |
| 162 | + paddle.set_device(paddle.get_device()) |
| 163 | + self.executor._init_from_path( |
| 164 | + self.config.model, self.config.lang, self.config.sample_rate, |
| 165 | + self.config.cfg_path, self.config.decode_method, |
| 166 | + self.config.ckpt_path) |
| 167 | + except: |
| 168 | + logger.info("Initialize ASR server engine Failed.") |
| 169 | + return False |
| 170 | + |
| 171 | + logger.info("Initialize ASR server engine successfully.") |
| 172 | + return True |
36 | 173 |
|
37 |
| - def run(self): |
38 |
| - logger.info("start run asr engine") |
39 |
| - return "hello world" |
| 174 | + def run(self, audio_data): |
| 175 | + """engine run |
| 176 | +
|
| 177 | + Args: |
| 178 | + audio_data (bytes): base64.b64decode |
| 179 | + """ |
| 180 | + if self.executor._check( |
| 181 | + io.BytesIO(audio_data), self.config.sample_rate, |
| 182 | + self.config.force_yes): |
| 183 | + logger.info("start run asr engine") |
| 184 | + self.executor.preprocess(self.config.model, io.BytesIO(audio_data)) |
| 185 | + self.executor.infer(self.config.model) |
| 186 | + self.output = self.executor.postprocess() # Retrieve result of asr. |
| 187 | + else: |
| 188 | + logger.info("file check failed!") |
| 189 | + self.output = None |
| 190 | + |
| 191 | + def postprocess(self): |
| 192 | + """postprocess |
| 193 | + """ |
| 194 | + return self.output |
0 commit comments