asr_api.py 2.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 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.
import base64
15 16
import traceback
from typing import Union
L
lym0302 已提交
17

18
from fastapi import APIRouter
19

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 ASRRequest
from paddlespeech.server.restful.response import ASRResponse
from paddlespeech.server.restful.response import ErrorResponse
from paddlespeech.server.utils.errors import ErrorCode
from paddlespeech.server.utils.errors import failed_response
from paddlespeech.server.utils.exception import ServerBaseException
27

28
router = APIRouter()
29

30

31 32 33 34 35 36 37
@router.get('/paddlespeech/asr/help')
def help():
    """help

    Returns:
        json: [description]
    """
38 39 40 41 42 43 44
    response = {
        "success": "True",
        "code": 200,
        "message": {
            "global": "success"
        },
        "result": {
W
WilliamZhang06 已提交
45
            "description": "asr server",
46 47 48 49 50
            "input": "base64 string of wavfile",
            "output": "transcription"
        }
    }
    return response
51 52


53 54
@router.post(
    "/paddlespeech/asr", response_model=Union[ASRResponse, ErrorResponse])
55 56 57 58 59 60 61 62 63
def asr(request_body: ASRRequest):
    """asr api 

    Args:
        request_body (ASRRequest): [description]

    Returns:
        json: [description]
    """
64 65
    try:
        audio_data = base64.b64decode(request_body.audio)
66 67 68 69 70

        # get single engine from engine pool
        engine_pool = get_engine_pool()
        asr_engine = engine_pool['asr']

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
        asr_engine.run(audio_data)
        asr_results = asr_engine.postprocess()

        response = {
            "success": True,
            "code": 200,
            "message": {
                "description": "success"
            },
            "result": {
                "transcription": asr_results
            }
        }

    except ServerBaseException as e:
        response = failed_response(e.error_code, e.msg)
L
lym0302 已提交
87
    except BaseException:
88 89 90 91
        response = failed_response(ErrorCode.SERVER_UNKOWN_ERR)
        traceback.print_exc()

    return response