tts_api.py 3.9 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.
L
lym0302 已提交
14
import traceback
15
from typing import Union
L
lym0302 已提交
16

W
WilliamZhang06 已提交
17 18
from fastapi import APIRouter

L
lym0302 已提交
19
from paddlespeech.cli.log import logger
L
lym0302 已提交
20
from paddlespeech.server.engine.engine_pool import get_engine_pool
L
lym0302 已提交
21 22 23 24 25 26
from paddlespeech.server.restful.request import TTSRequest
from paddlespeech.server.restful.response import ErrorResponse
from paddlespeech.server.restful.response import TTSResponse
from paddlespeech.server.utils.errors import ErrorCode
from paddlespeech.server.utils.errors import failed_response
from paddlespeech.server.utils.exception import ServerBaseException
W
WilliamZhang06 已提交
27

W
WilliamZhang06 已提交
28
router = APIRouter()
W
WilliamZhang06 已提交
29 30


W
WilliamZhang06 已提交
31 32 33
@router.get('/paddlespeech/tts/help')
def help():
    """help
W
WilliamZhang06 已提交
34

W
WilliamZhang06 已提交
35 36 37
    Returns:
        json: [description]
    """
L
lym0302 已提交
38
    response = {
L
lym0302 已提交
39
        "success": "True",
L
lym0302 已提交
40
        "code": 200,
L
lym0302 已提交
41 42 43 44 45 46 47 48 49
        "message": {
            "global": "success"
        },
        "result": {
            "description": "tts server",
            "text": "sentence to be synthesized",
            "audio": "the base64 of audio"
        }
    }
L
lym0302 已提交
50
    return response
W
WilliamZhang06 已提交
51 52


53 54
@router.post(
    "/paddlespeech/tts", response_model=Union[TTSResponse, ErrorResponse])
L
lym0302 已提交
55 56 57 58 59 60 61 62 63
def tts(request_body: TTSRequest):
    """tts api

    Args:
        request_body (TTSRequest): [description]

    Returns:
        json: [description]
    """
L
lym0302 已提交
64 65 66

    logger.info("request: {}".format(request_body))

L
lym0302 已提交
67 68 69 70 71 72 73
    # get params
    text = request_body.text
    spk_id = request_body.spk_id
    speed = request_body.speed
    volume = request_body.volume
    sample_rate = request_body.sample_rate
    save_path = request_body.save_path
L
lym0302 已提交
74

L
lym0302 已提交
75
    # Check parameters
L
lym0302 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
    if speed <= 0 or speed > 3:
        return failed_response(
            ErrorCode.SERVER_PARAM_ERR,
            "invalid speed value, the value should be between 0 and 3.")
    if volume <= 0 or volume > 3:
        return failed_response(
            ErrorCode.SERVER_PARAM_ERR,
            "invalid volume value, the value should be between 0 and 3.")
    if sample_rate not in [0, 16000, 8000]:
        return failed_response(
            ErrorCode.SERVER_PARAM_ERR,
            "invalid sample_rate value, the choice of value is 0, 8000, 16000.")
    if save_path is not None and not save_path.endswith(
            "pcm") and not save_path.endswith("wav"):
        return failed_response(
            ErrorCode.SERVER_PARAM_ERR,
            "invalid save_path, saved audio formats support pcm and wav")
L
lym0302 已提交
93

L
lym0302 已提交
94 95
    # run
    try:
L
lym0302 已提交
96 97 98
        # get single engine from engine pool
        engine_pool = get_engine_pool()
        tts_engine = engine_pool['tts']
L
lym0302 已提交
99
        logger.info("Get tts engine successfully.")
L
lym0302 已提交
100

L
lym0302 已提交
101
        lang, target_sample_rate, wav_base64 = tts_engine.run(
L
lym0302 已提交
102
            text, spk_id, speed, volume, sample_rate, save_path)
L
lym0302 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

        response = {
            "success": True,
            "code": 200,
            "message": {
                "description": "success."
            },
            "result": {
                "lang": lang,
                "spk_id": spk_id,
                "speed": speed,
                "volume": volume,
                "sample_rate": target_sample_rate,
                "save_path": save_path,
                "audio": wav_base64
            }
        }
L
lym0302 已提交
120 121
    except ServerBaseException as e:
        response = failed_response(e.error_code, e.msg)
L
lym0302 已提交
122
    except BaseException:
L
lym0302 已提交
123 124
        response = failed_response(ErrorCode.SERVER_UNKOWN_ERR)
        traceback.print_exc()
L
lym0302 已提交
125

L
lym0302 已提交
126
    return response