improve cli code, test=doc

pull/1470/head
lym0302 3 years ago
parent 2bf4b4521f
commit 42cbe313c2

@ -13,9 +13,12 @@
# limitations under the License. # limitations under the License.
import _locale import _locale
from .base_commands import BaseCommand from .base_commands import ClientBaseCommand
from .base_commands import HelpCommand from .base_commands import ClientHelpCommand
from paddlespeech.server.bin.paddlespeech_client import TTSClientExecutor from .base_commands import ServerBaseCommand
from paddlespeech.server.bin.paddlespeech_server import ServerExecutor from .base_commands import ServerHelpCommand
from .bin.paddlespeech_client import ASRClientExecutor
from .bin.paddlespeech_client import TTSClientExecutor
from .bin.paddlespeech_server import ServerExecutor
_locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8']) _locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8'])

@ -13,30 +13,63 @@
# limitations under the License. # limitations under the License.
from typing import List from typing import List
from .entry import commands from .entry import client_commands
from .util import cli_register from .entry import server_commands
from .util import get_command from .util import cli_client_register
from .util import cli_server_register
from .util import get_client_command
from .util import get_server_command
__all__ = [ __all__ = [
'BaseCommand', 'ServerBaseCommand',
'HelpCommand', 'ServerHelpCommand',
'ClientBaseCommand',
'ClientHelpCommand',
] ]
@cli_register(name='paddleserver') @cli_server_register(name='paddlespeech_server')
class BaseCommand: class ServerBaseCommand:
def execute(self, argv: List[str]) -> bool: def execute(self, argv: List[str]) -> bool:
help = get_command('paddleserver.help') help = get_server_command('paddlespeech_server.help')
return help().execute(argv) return help().execute(argv)
@cli_register(name='paddleserver.help', description='Show help for commands.') @cli_server_register(
class HelpCommand: name='paddlespeech_server.help', description='Show help for commands.')
class ServerHelpCommand:
def execute(self, argv: List[str]) -> bool: def execute(self, argv: List[str]) -> bool:
msg = 'Usage:\n' msg = 'Usage:\n'
msg += ' paddleserver <command> <options>\n\n' msg += ' paddlespeech_server <command> <options>\n\n'
msg += 'Commands:\n' msg += 'Commands:\n'
for command, detail in commands['paddleserver'].items(): for command, detail in server_commands['paddlespeech_server'].items():
if command.startswith('_'):
continue
if '_description' not in detail:
continue
msg += ' {:<15} {}\n'.format(command,
detail['_description'])
print(msg)
return True
@cli_client_register(name='paddlespeech_client')
class ClientBaseCommand:
def execute(self, argv: List[str]) -> bool:
help = get_client_command('paddlespeech_client.help')
return help().execute(argv)
@cli_client_register(
name='paddlespeech_client.help', description='Show help for commands.')
class ClientHelpCommand:
def execute(self, argv: List[str]) -> bool:
msg = 'Usage:\n'
msg += ' paddlespeech_client <command> <options>\n\n'
msg += 'Commands:\n'
for command, detail in client_commands['paddlespeech_client'].items():
if command.startswith('_'): if command.startswith('_'):
continue continue

@ -11,4 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from .paddlespeech_client import ASRClientExecutor
from .paddlespeech_client import TTSClientExecutor
from .paddlespeech_server import ServerExecutor from .paddlespeech_server import ServerExecutor

@ -24,11 +24,15 @@ import numpy as np
import requests import requests
import soundfile import soundfile
from paddlespeech.server.util import cli_register from ..util import cli_client_register
from paddlespeech.server.utils.audio_process import wav2pcm from paddlespeech.server.utils.audio_process import wav2pcm
from paddlespeech.server.utils.util import wav2base64
__all__ = ['TTSClientExecutor', 'ASRClientExecutor']
@cli_register(name='paddleserver.ttsclient', description='visit tts service')
@cli_client_register(
name='paddlespeech_client.tts', description='visit tts service')
class TTSClientExecutor(): class TTSClientExecutor():
def __init__(self): def __init__(self):
super().__init__() super().__init__()
@ -79,6 +83,7 @@ class TTSClientExecutor():
response = requests.post(url, json.dumps(request)) response = requests.post(url, json.dumps(request))
response_dict = response.json() response_dict = response.json()
print(response_dict["message"])
wav_base64 = response_dict["result"]["audio"] wav_base64 = response_dict["result"]["audio"]
audio_data_byte = base64.b64decode(wav_base64) audio_data_byte = base64.b64decode(wav_base64)
@ -107,6 +112,45 @@ class TTSClientExecutor():
samples_length, sample_rate = self.tts_client(args) samples_length, sample_rate = self.tts_client(args)
time_consume = time.time() - st time_consume = time.time() - st
print("Save synthesized audio successfully on %s." % (args.output)) print("Save synthesized audio successfully on %s." % (args.output))
print("Inference time: %f" % (time_consume)) print("Inference time: %f s." % (time_consume))
except: except:
print("Failed to synthesized audio.") print("Failed to synthesized audio.")
@cli_client_register(
name='paddlespeech_client.asr', description='visit asr service')
class ASRClientExecutor():
def __init__(self):
super().__init__()
self.parser = argparse.ArgumentParser()
self.parser.add_argument(
'--server_ip', type=str, default='127.0.0.1', help='server ip')
self.parser.add_argument(
'--port', type=int, default=8090, help='server port')
self.parser.add_argument(
'--audio_file',
type=str,
default="./paddlespeech/server/tests/16_audio.wav",
help='Audio file to be recognized')
self.parser.add_argument(
'--sample_rate', type=int, default=16000, help='audio sample rate')
def execute(self, argv: List[str]) -> bool:
args = self.parser.parse_args(argv)
url = 'http://' + args.server_ip + ":" + str(
args.port) + '/paddlespeech/asr'
audio = wav2base64(args.audio_file)
data = {
"audio": audio,
"audio_format": "wav",
"sample_rate": args.sample_rate,
"lang": "zh_cn",
}
time_start = time.time()
try:
r = requests.post(url=url, data=json.dumps(data))
# ending Timestamp
time_end = time.time()
print('time cost', time_end - time_start, 's')
except:
print("Failed to speech recognition.")

@ -17,16 +17,19 @@ from typing import List
import uvicorn import uvicorn
from fastapi import FastAPI from fastapi import FastAPI
from ..util import cli_server_register
from paddlespeech.server.engine.engine_factory import EngineFactory from paddlespeech.server.engine.engine_factory import EngineFactory
from paddlespeech.server.restful.api import setup_router from paddlespeech.server.restful.api import setup_router
from paddlespeech.server.util import cli_register
from paddlespeech.server.utils.config import get_config from paddlespeech.server.utils.config import get_config
__all__ = ['ServerExecutor']
app = FastAPI( app = FastAPI(
title="PaddleSpeech Serving API", description="Api", version="0.0.1") title="PaddleSpeech Serving API", description="Api", version="0.0.1")
@cli_register(name='paddleserver.server', description='Start the service') @cli_server_register(
name='paddlespeech_server.server', description='Start the service')
class ServerExecutor(): class ServerExecutor():
def __init__(self): def __init__(self):
super().__init__() super().__init__()

@ -14,18 +14,33 @@
import sys import sys
from collections import defaultdict from collections import defaultdict
__all__ = ['commands'] __all__ = ['server_commands', 'client_commands']
def _CommandDict(): def _CommandDict():
return defaultdict(_CommandDict) return defaultdict(_CommandDict)
def _execute(): def server_execute():
com = commands com = server_commands
idx = 0
for _argv in (['paddlespeech_server'] + sys.argv[1:]):
if _argv not in com:
break
idx += 1
com = com[_argv]
# The method 'execute' of a command instance returns 'True' for a success
# while 'False' for a failure. Here converts this result into a exit status
# in bash: 0 for a success and 1 for a failure.
status = 0 if com['_entry']().execute(sys.argv[idx:]) else 1
return status
def client_execute():
com = client_commands
idx = 0 idx = 0
for _argv in (['paddleserver'] + sys.argv[1:]): for _argv in (['paddlespeech_client'] + sys.argv[1:]):
if _argv not in com: if _argv not in com:
break break
idx += 1 idx += 1
@ -38,4 +53,5 @@ def _execute():
return status return status
commands = _CommandDict() server_commands = _CommandDict()
client_commands = _CommandDict()

@ -31,24 +31,27 @@ from paddle.framework import load
import paddleaudio import paddleaudio
from . import download from . import download
from .. import __version__ from .. import __version__
from .entry import commands from .entry import client_commands
from .entry import server_commands
requests.adapters.DEFAULT_RETRIES = 3 requests.adapters.DEFAULT_RETRIES = 3
__all__ = [ __all__ = [
'cli_register', 'cli_server_register',
'get_command', 'get_server_command',
'cli_client_register',
'get_client_command',
'download_and_decompress', 'download_and_decompress',
'load_state_dict_from_url', 'load_state_dict_from_url',
'stats_wrapper', 'stats_wrapper',
] ]
def cli_register(name: str, description: str='') -> Any: def cli_server_register(name: str, description: str='') -> Any:
def _warpper(command): def _warpper(command):
items = name.split('.') items = name.split('.')
com = commands com = server_commands
for item in items: for item in items:
com = com[item] com = com[item]
com['_entry'] = command com['_entry'] = command
@ -59,9 +62,33 @@ def cli_register(name: str, description: str='') -> Any:
return _warpper return _warpper
def get_command(name: str) -> Any: def get_server_command(name: str) -> Any:
items = name.split('.') items = name.split('.')
com = commands com = server_commands
for item in items:
com = com[item]
return com['_entry']
def cli_client_register(name: str, description: str='') -> Any:
def _warpper(command):
items = name.split('.')
com = client_commands
for item in items:
com = com[item]
com['_entry'] = command
if description:
com['_description'] = description
return command
return _warpper
def get_client_command(name: str) -> Any:
items = name.split('.')
com = client_commands
for item in items: for item in items:
com = com[item] com = com[item]

@ -236,7 +236,8 @@ setup_info = dict(
entry_points={ entry_points={
'console_scripts': [ 'console_scripts': [
'paddlespeech=paddlespeech.cli.entry:_execute', 'paddlespeech=paddlespeech.cli.entry:_execute',
'paddleserver=paddlespeech.server.entry:_execute' 'paddlespeech_server=paddlespeech.server.entry:server_execute',
'paddlespeech_client=paddlespeech.server.entry:client_execute'
] ]
}) })

Loading…
Cancel
Save