Help Center/ Speech Interaction Service/ SDK Reference/ Python SDKs/ HTTP API for Short Sentence Recognition
Updated on 2024-03-05 GMT+08:00

HTTP API for Short Sentence Recognition

Prerequisites

  • You have completed the configurations as instructed in Configuring the Python Environment. Python SDKs support only Python 3.
  • Ensure that the audio file to be recognized exists. If needed, you can obtain the sample audio file from the downloaded SDK package.

Initializing Client

For details about AsrCustomizationClient initialization, see Table 1.

Table 1 AsrCustomizationClient initialization parameters

Name

Mandatory

Type

Description

ak

Yes

String

AK of the user. For details, see AK/SK-Based Authentication.

sk

Yes

String

SK of the user. For details, see AK/SK-Based Authentication.

region

Yes

String

Region, for example, ap-southeast-3. For details, see Endpoints.

project_id

Yes

String

Project ID corresponding to the region. For details about how to obtain a project ID, see Obtaining a Project ID.

service_endpoint

No

String

Endpoint. You can use the default value.

sis_config

No

Object

For details, see Table 2.

Table 2 SisConfig

Name

Mandatory

Type

Description

connect_timeout

No

Integer

Connection timeout interval (s). The default value is 10s.

read_timeout

No

Integer

Read timeout interval (s). The default value is 10s.

proxy

No

List

[host, port] or [host, port, username, password].

Request Parameters

The request class is AsrCustomShortRequest. For details, see Table 3.

Table 3 AsrCustomShortRequest

Name

Mandatory

Type

Description

data

Yes

String

Base64-encoded character string of the local audio file. The audio duration must be within 30 seconds.

audio_format

Yes

String

Audio format. For details, see Sentence Transcription in SIS API Reference.

model_property

Yes

String

Property string in "language_sampling rate_model" format, for example, english_8k_common. For details, see Short Sentence Recognition in SIS API Reference.

add_punc

No

String

Whether to add punctuation marks to the recognition result. Possible values are yes and no. The default value is no.

Response Parameters

The responses of Python SDKs are in JSON format. For details, see Table 4.

Table 4 Response result

Name

Mandatory

Type

Description

result

Yes

Object

For details, see Table 5.

trace_id

Yes

String

ID used for fault tracing in background logs.

Table 5 Result

Name

Mandatory

Type

Description

text

Yes

String

Recognition result

score

Yes

Float

Recognition result confidence

Sample Code

The following example is for reference only. Obtain and run the latest code in section Obtaining SDKs.

# -*- coding: utf-8 -*-
from huaweicloud_sis.client.asr_client import AsrCustomizationClient
from huaweicloud_sis.bean.asr_request import AsrCustomShortRequest
from huaweicloud_sis.exception.exceptions import ClientException
from huaweicloud_sis.exception.exceptions import ServerException
from huaweicloud_sis.utils import io_utils
from huaweicloud_sis.bean.sis_config import SisConfig
import json
import os
# Authentication parameters
# Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK and store them in the configuration file or environment variables.
# In this example, the AK and SK are stored in environment variables. Before running this example, set environment variables HUAWEICLOUD_SIS_AK or HUAWEICLOUD_SIS_SK.
ak = os.getenv("HUAWEICLOUD_SIS_AK")            
assert ak is not None, "Please add ak in your develop environment"
sk = os.getenv("HUAWEICLOUD_SIS_SK")            
assert sk is not None, "Please add sk in your develop environment"
project_id = ""     # Correspond to the region.
region = ''         # region, for example, ap-southeast-3
"""
    todo Enter the correct audio format and model property character string.
   1. The audio formats must match.
         For example, for a WAV audio file, set the format to WAV. For details, see the API document.
         If the audio format is PCM and the sampling rate is 8 kHz, enter pcm8k16bit.
         If "audio_format is invalid" is returned, the file format is not supported. For details about the supported audio formats, see the API Reference.
    2. The audio sampling rate must match the sampling rate of the attribute character string.
         If the format is pcm16k16bit but the attribute character string is set to chinese_8k_common, "'audio_format' is not match model" is returned.
         If the sampling rate of the WAV file is 16 kHz but the attribute character string is set to chinese_8k_common, "'audio_format' is not match model" is returned.
"""
# Sentence Transcription parameters, which are passed through the Base64 code of the audio file. The audio duration must be within 1 minute.
path = ''                               # File location, which must be specific to a file, for example, D:/test.wav.
path_audio_format = ''                  # Audio format, for example, WAV. For details, see the API Reference.
path_property = 'chinese_16k_general'   # language_sampleRate_domain, for example, chinese_16k_general. For details, see the API Reference.
def sasr_example():
    """ Sentence Transcription demo """
    # Step 1 Initialize the client.
    config = SisConfig()
    config.set_connect_timeout(10)  # Set the connection timeout interval.
    config.set_read_timeout(10)  # Set the read timeout interval.
    # Set the proxy. Ensure that the proxy is available before using it. The proxy format can be [host, port] or [host, port, username, password].
    # config.set_proxy(proxy)
    asr_client = AsrCustomizationClient(ak, sk, region, project_id, sis_config=config)
    # Step 2 Construct a request.
    data = io_utils.encode_file(path)
    asr_request = AsrCustomShortRequest(path_audio_format, path_property, data)
    # You can use the default values for all parameters.
    # Set whether to add punctuation marks. Possible values are yes and no. The default value is no.
    asr_request.set_add_punc('yes')
    # Set whether to convert numbers in the speech into Arabic numerals. Possible values are yes and no. The default value is yes.
    asr_request.set_digit_norm('yes')
    # Set whether to add the hot word table ID. If no hot word table ID is added, leave this parameter blank.
    # asr_request.set_vocabulary_id(None)
    # Set whether word_info is required. The value can be yes or no. The default value is no.
    asr_request.set_need_word_info('no')
    # Step 3 Send the request and the result is returned in JSON format.
    result = asr_client.get_short_response(asr_request)
    print(json.dumps(result, indent=2, ensure_ascii=False))
if __name__ == '__main__':
    try:
        sasr_example()
    except ClientException as e:
        print(e)
    except ServerException as e:
        print(e)