paddlespeech_client.py 5.8 KB
Newer Older
L
lym0302 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
# 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 base64
import io
import json
import os
import random
import time
from typing import List

import numpy as np
import requests
import soundfile

L
lym0302 已提交
27
from ..executor import BaseExecutor
L
lym0302 已提交
28
from ..util import cli_client_register
L
lym0302 已提交
29
from paddlespeech.server.utils.audio_process import wav2pcm
L
lym0302 已提交
30
from paddlespeech.server.utils.util import wav2base64
L
lym0302 已提交
31

L
lym0302 已提交
32
__all__ = ['TTSClientExecutor', 'ASRClientExecutor']
L
lym0302 已提交
33

L
lym0302 已提交
34 35 36

@cli_client_register(
    name='paddlespeech_client.tts', description='visit tts service')
L
lym0302 已提交
37
class TTSClientExecutor(BaseExecutor):
L
lym0302 已提交
38 39 40 41 42 43 44 45
    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(
L
lym0302 已提交
46
            '--input',
L
lym0302 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
            type=str,
            default="你好,欢迎使用语音合成服务",
            help='A sentence to be synthesized')
        self.parser.add_argument(
            '--spk_id', type=int, default=0, help='Speaker id')
        self.parser.add_argument(
            '--speed', type=float, default=1.0, help='Audio speed')
        self.parser.add_argument(
            '--volume', type=float, default=1.0, help='Audio volume')
        self.parser.add_argument(
            '--sample_rate',
            type=int,
            default=0,
            help='Sampling rate, the default is the same as the model')
        self.parser.add_argument(
            '--output',
            type=str,
L
lym0302 已提交
64
            default="./output.wav",
L
lym0302 已提交
65 66 67 68 69 70
            help='Synthesized audio file')

    # Request and response
    def tts_client(self, args):
        """ Request and response
        Args:
L
lym0302 已提交
71
            input: A sentence to be synthesized
L
lym0302 已提交
72 73 74 75 76
            outfile: Synthetic audio file
        """
        url = 'http://' + args.server_ip + ":" + str(
            args.port) + '/paddlespeech/tts'
        request = {
L
lym0302 已提交
77
            "text": args.input,
L
lym0302 已提交
78 79 80 81 82 83 84 85 86
            "spk_id": args.spk_id,
            "speed": args.speed,
            "volume": args.volume,
            "sample_rate": args.sample_rate,
            "save_path": args.output
        }

        response = requests.post(url, json.dumps(request))
        response_dict = response.json()
L
lym0302 已提交
87
        print(response_dict["message"])
L
lym0302 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
        wav_base64 = response_dict["result"]["audio"]

        audio_data_byte = base64.b64decode(wav_base64)
        # from byte
        samples, sample_rate = soundfile.read(
            io.BytesIO(audio_data_byte), dtype='float32')

        # transform audio
        outfile = args.output
        if outfile.endswith(".wav"):
            soundfile.write(outfile, samples, sample_rate)
        elif outfile.endswith(".pcm"):
            temp_wav = str(random.getrandbits(128)) + ".wav"
            soundfile.write(temp_wav, samples, sample_rate)
            wav2pcm(temp_wav, outfile, data_type=np.int16)
            os.system("rm %s" % (temp_wav))
        else:
            print("The format for saving audio only supports wav or pcm")

        return len(samples), sample_rate

    def execute(self, argv: List[str]) -> bool:
        args = self.parser.parse_args(argv)
        st = time.time()
        try:
            samples_length, sample_rate = self.tts_client(args)
            time_consume = time.time() - st
            print("Save synthesized audio successfully on %s." % (args.output))
L
lym0302 已提交
116
            print("Inference time: %f s." % (time_consume))
L
lym0302 已提交
117 118
        except:
            print("Failed to synthesized audio.")
L
lym0302 已提交
119 120 121 122


@cli_client_register(
    name='paddlespeech_client.asr', description='visit asr service')
L
lym0302 已提交
123
class ASRClientExecutor(BaseExecutor):
L
lym0302 已提交
124 125 126 127 128 129 130 131
    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(
L
lym0302 已提交
132
            '--input',
L
lym0302 已提交
133 134 135 136 137
            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')
L
lym0302 已提交
138 139 140 141
        self.parser.add_argument(
            '--lang', type=str, default="zh_cn", help='language')
        self.parser.add_argument(
            '--audio_format', type=str, default="wav", help='audio format')
L
lym0302 已提交
142 143 144 145 146

    def execute(self, argv: List[str]) -> bool:
        args = self.parser.parse_args(argv)
        url = 'http://' + args.server_ip + ":" + str(
            args.port) + '/paddlespeech/asr'
L
lym0302 已提交
147
        audio = wav2base64(args.input)
L
lym0302 已提交
148 149
        data = {
            "audio": audio,
L
lym0302 已提交
150
            "audio_format": args.audio_format,
L
lym0302 已提交
151
            "sample_rate": args.sample_rate,
L
lym0302 已提交
152
            "lang": args.lang,
L
lym0302 已提交
153 154 155 156 157 158
        }
        time_start = time.time()
        try:
            r = requests.post(url=url, data=json.dumps(data))
            # ending Timestamp
            time_end = time.time()
L
lym0302 已提交
159
            print(r.json())
L
lym0302 已提交
160 161 162
            print('time cost', time_end - time_start, 's')
        except:
            print("Failed to speech recognition.")