Skip to content

Commit 1219537

Browse files
authored
Merge pull request #1413 from WilliamZhang06/server
[Server] added asr engine
2 parents 1cf0bdb + 88f9c81 commit 1219537

File tree

17 files changed

+295
-68
lines changed

17 files changed

+295
-68
lines changed

speechserving/speechserving/conf/application.yaml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ port: 8090
1010
# CONFIG FILE #
1111
##################################################################
1212
# add engine type (Options: asr, tts) and config file here.
13+
1314
engine_backend:
1415
asr: 'conf/asr/asr.yaml'
1516
tts: 'conf/tts/tts.yaml'
17+
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
model: 'conformer_wenetspeech'
22
lang: 'zh'
33
sample_rate: 16000
4+
cfg_path:
5+
ckpt_path:
46
decode_method: 'attention_rescoring'
7+
force_yes: False

speechserving/speechserving/engine/asr/python/asr_engine.py

Lines changed: 166 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,29 +11,184 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# 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
1423
from engine.base_engine import BaseEngine
1524

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
1731
from utils.config import get_config
1832

1933
__all__ = ['ASREngine']
2034

2135

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+
22137
class ASREngine(BaseEngine):
138+
"""ASR server engine
139+
140+
Args:
141+
metaclass: Defaults to Singleton.
142+
"""
143+
23144
def __init__(self):
24145
super(ASREngine, self).__init__()
25146

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+
"""
29156
self.input = None
30157
self.output = None
31-
config = get_config(self.config_file)
32-
pass
158+
self.executor = ASRServerExecutor()
33159

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
36173

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

speechserving/speechserving/engine/base_engine.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818

1919
from pattern_singleton import Singleton
2020

21+
__all__ = ['BaseEngine']
22+
2123

2224
class BaseEngine(metaclass=Singleton):
2325
"""

speechserving/speechserving/engine/engine_factory.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,18 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
from typing import Text
15+
1416
from engine.asr.python.asr_engine import ASREngine
1517
from engine.tts.python.tts_engine import TTSEngine
1618

1719

20+
__all__ = ['EngineFactory']
21+
22+
1823
class EngineFactory(object):
1924
@staticmethod
20-
def get_engine(engine_name):
25+
def get_engine(engine_name: Text):
2126
if engine_name == 'asr':
2227
return ASREngine()
2328
elif engine_name == 'tts':

speechserving/speechserving/main.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,32 +12,40 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414
import argparse
15+
1516
import uvicorn
1617
import yaml
18+
from engine.engine_factory import EngineFactory
1719
from fastapi import FastAPI
18-
1920
from restful.api import setup_router
20-
from utils.log import logger
21+
2122
from utils.config import get_config
22-
from engine.engine_factory import EngineFactory
23+
from utils.log import logger
2324

2425
app = FastAPI(
2526
title="PaddleSpeech Serving API", description="Api", version="0.0.1")
2627

2728

2829
def init(config):
29-
""" system initialization
30+
"""system initialization
31+
32+
Args:
33+
config (CfgNode): config object
34+
35+
Returns:
36+
bool:
3037
"""
3138
# init api
3239
api_list = list(config.engine_backend)
3340
api_router = setup_router(api_list)
3441
app.include_router(api_router)
3542

3643
# init engine
37-
engine_list = []
44+
engine_pool = []
3845
for engine in config.engine_backend:
39-
engine_list.append(EngineFactory.get_engine(engine_name=engine))
40-
engine_list[-1].init(config_file=config.engine_backend[engine])
46+
engine_pool.append(EngineFactory.get_engine(engine_name=engine))
47+
if not engine_pool[-1].init(config_file=config.engine_backend[engine]):
48+
return False
4149

4250
return True
4351

speechserving/speechserving/restful/api.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,15 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414
from typing import List
15+
1516
from fastapi import APIRouter
1617

17-
from .tts_api import router as tts_router
1818
from .asr_api import router as asr_router
19+
from .tts_api import router as tts_router
1920

2021
_router = APIRouter()
2122

23+
2224
def setup_router(api_list: List):
2325

2426
for api_name in api_list:
@@ -30,4 +32,3 @@ def setup_router(api_list: List):
3032
pass
3133

3234
return _router
33-

0 commit comments

Comments
 (0)