Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
Help Center/ Speech Interaction Service/ SDK Reference/ Python SDKs/ HTTP API for Short Sentence Recognition

HTTP API for Short Sentence Recognition

Updated on 2024-03-05 GMT+08:00

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)

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback