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/ Java 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 Java Environment.
  • 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

Initialize AsrCustomizationClient. Its parameters include AuthInfo and SisConfig.

Table 1 AuthInfo

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.

projectId

Yes

String

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

endpoint

No

String

Endpoint. Generally, the default value is used.

Table 2 SisConfig

Name

Mandatory

Type

Description

connectionTimeout

No

Integer

Connection timeout interval (ms). The default value is 10000ms.

readTimeout

No

Integer

Read timeout interval (ms). The default value is 10000ms.

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.

audioFormat

Yes

String

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

property

Yes

String

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

addPunc

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 response class is AsrCustomShortResponse. For details, see Table 4.

Table 4 AsrCustomShortResponse

Name

Mandatory

Type

Description

trace_id

Yes

String

Service internal token used to trace a specific process in logs. This parameter is not included when the API fails to be called.

In some error cases, this field may not exist.

result

Yes

Object

Recognition result when the API is successfully called. In the case of an API calling failure, this parameter is not included. For details, see Table 5.

Table 5 Result

Name

Mandatory

Type

Description

text

Yes

String

Recognition result of a successful call.

score

Yes

Float

Confidence of a successful call. The value ranges from 0 to 1.

Sample Code

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

import com.huawei.sis.bean.SisConfig;
import com.huawei.sis.bean.SisConstant;
import com.huawei.sis.bean.request.AsrCustomShortRequest;
import com.huawei.sis.bean.response.AsrCustomShortResponse;
import com.huawei.sis.bean.AuthInfo;
import com.huawei.sis.client.AsrCustomizationClient;
import com.huawei.sis.exception.SisException;
import com.huawei.sis.util.IOUtils;
import java.util.List;
import com.huawei.sis.util.JsonUtils;


/**
 * Short Sentence Recognition
 *
 * Copyright 2021 Huawei Technologies Co.,Ltd.
 */
public class AsrCustomizationDemo {
  private static final int SLEEP_TIME = 500;
  private static final int MAX_POLLING_NUMS = 1000;

  // 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 for identity authentication. Before running this example, configure environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK.
  private String ak = System.getenv("HUAWEICLOUD_SDK_AK");
  private String sk = System.getenv("HUAWEICLOUD_SDK_SK");
  

  private String region = "";    // Region, such as ap-southeast-3
  private String projectId = ""; // Project ID corresponding to the region. Log in to the management console, move the cursor over your username in the upper right corner, and choose My Credentials from the drop-down list. On the displayed page, view the project ID. If there are multiple projects, expand Region and obtain the sub-project ID from the Project ID column.
* 
  // Sentence Transcription parameters
  private String path = "";             // Audio file path, for example, D:/test.wav. The SDK converts the audio file into a Base64-encoded file.
  private String pathAudioFormat = "";  // File format, for example, WAV.
  private String pathProperty = "chinese_16k_general";     // Attribute string, language_sampleRate_domain. chinese_16k_general is recommended for 16 kHZ models.


  /**
   * Configure Sentence Transcription parameters. All parameters have default values. You can use them without configuring their values.
   *
   * @param request Sentence Transcription request
   */
  private void setShortParameter(AsrCustomShortRequest request) {

    // Set whether to add punctuation marks. The default value is no.
    request.setAddPunc("yes");
  }

  /**
   * Define config. All parameters are optional. Set the timeout intervals.
   *
   * @return SisConfig
   */
  private SisConfig getConfig() {
    SisConfig config = new SisConfig();
    // Set the connection timeout interval. The default value is 10000 ms.
    config.setConnectionTimeout(SisConstant.DEFAULT_CONNECTION_TIMEOUT);
   // Set the read timeout interval. The default value is 10000 ms.
    config.setReadTimeout(SisConstant.DEFAULT_READ_TIMEOUT);
    // Set the proxy. Ensure that the proxy is available before setting it. The unencrypted proxy can also be used for proxy initialization, for example, new ProxyHostInfo(host, port).
    // ProxyHostInfo proxy = new ProxyHostInfo(host, port, username, password);
    // config.setProxy(proxy);
    return config;
  }


  /**
   * Sentence Transcription demo
   */
  private void shortDemo() {
    try {
      // 1. Initialize the AsrCustomizationClient.
      // Define authInfo based on the ak, sk, region, and projectId parameters.
      AuthInfo authInfo = new AuthInfo(ak, sk, region, projectId);
      // Set config, which is related to timeout settings.
      SisConfig config = getConfig();
      // Construct the AsrCustomizationClient based on authInfo and config.
      AsrCustomizationClient asr = new AsrCustomizationClient(authInfo, config);

      // 2. Configure the request.
      String data = IOUtils.getEncodeDataByPath(path);
      AsrCustomShortRequest request = new AsrCustomShortRequest(data, pathAudioFormat, pathProperty);
      // Set request parameters. All parameters are optional.
      setShortParameter(request);

      // 3. Send the request and obtain a response.
      AsrCustomShortResponse response = asr.getAsrShortResponse(request);
      // Print the result.
      System.out.println(JsonUtils.obj2Str(response, true));

    } catch (SisException e) {
      e.printStackTrace();
      System.out.println("error_code:" + e.getErrorCode() + "\nerror_msg:" + e.getErrorMsg());
    }
  }

  public static void main(String[] args) {
    AsrCustomizationDemo demo = new AsrCustomizationDemo();
    demo.shortDemo();
  }

}

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