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/ Getting Started/ Calling the Java SDK to Use Short Sentence Recognition

Calling the Java SDK to Use Short Sentence Recognition

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

SIS SDKs encapsulate RESTful APIs provided by SIS to simplify development. You can directly call APIs provided by SIS SDKs to use the service capabilities.

This section uses Short Sentence Recognition as an example to show you how to use a Java SDK to access Huawei Cloud SIS. The procedure is as follows:

Step 1: Configuring the Environment

Step 2: Modifying Configuration Information

Step 3: Calling Short Sentence Recognition

Prerequisites

You have registered a Huawei ID and enabled Huawei Cloud services. Your account cannot be in arrears or frozen.

Subscribing to the Service

The Short Sentence Recognition service is now commercially available. You do not need to apply for OBT.

Maximum QPS: 3

Step 1: Configuring the Environment

  1. Download the SIS Java SDK.

    Download address: https://sis-open-data.obs.ap-southeast-3.myhuaweicloud.com/java/huaweicloud-java-sdk-sis-1.2.0.zip

  2. Prepare the Java development environment.
    • Download a JDK from the Oracle official website and install it. The 1.8 version is strongly recommended.
    • Download the latest version of Eclipse IDE for Java Developers (for example, eclipse-jee-mars-R-win32-x86_64.zip) from the Eclipse official website and install it.

    For details, see Configuring the Java Environment.

  3. Create an SIS Java SDK project.
    1. Decompress Eclipse and open it. Configure the JRE path correctly in Window > Preferences > Java > installed JREs.
    2. Create a project and choose New > Folder to create a folder named lib under the project. Copy the downloaded JAR file to the lib folder.
    3. Right-click the new project and choose Build Path > Configure Build Path from the shortcut menu. In the Java Build Path dialog box, click the Libraries tab and choose Add JARs. In the window that is displayed, select the JAR file that you just put in the lib folder. Click OK.

Step 2: Modifying Configuration Information

AK/SK- or token-based authentication can be used for the OCR Java SDK demo. In this example, AK/SK-based authentication is used.
  1. Obtain an AK/SK.

    The AK/SK is the access key. To obtain the AK/SK, log in to the My Credentials page and choose Access Keys > Add Access Key.

  2. For AK/SK-based authentication, configure the AK/SK in the OCR SDK for Java.

    Change the values of AK and SK of the function in the AsrCustomizationDemo.java file of the demo project to the obtained AK and SK, respectively.

  3. Set the parameters in the sample file AsrCustomizationDemo.java in the demo folder of the SDK. For details about the parameters, see Table 1, Table 2, and Table 3.
    import com.huawei.sis.bean.SisConfig;
    import com.huawei.sis.bean.SisConstant;
    import com.huawei.sis.bean.request.AsrCustomLongRequest;
    import com.huawei.sis.bean.response.AsrCustomLongResponse;
    import com.huawei.sis.bean.request.AsrCustomShortRequest;
    import com.huawei.sis.bean.response.AsrCustomShortResponse;
    import com.huawei.sis.bean.AuthInfo;
    import com.huawei.sis.bean.base.AsrcLongAnalysisInfo;
    import com.huawei.sis.bean.base.AsrcLongSentence;
    import com.huawei.sis.client.AsrCustomizationClient;
    import com.huawei.sis.exception.SisException;
    import com.huawei.sis.util.IOUtils;
    
    import java.util.List;
    
    /**
     * Short Sentence Recognition
     *
     * Copyright 2019 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
      private String projectId = ""; // Project ID. 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 My Credentials page, view the username and account name, and click the Projects tab to view the project ID. If there are multiple projects, expand Region and obtain the sub-project ID from the Project ID column.
      // Short Sentence Recognition parameters
      private String path = "";             // File path. Currently, only the Base64 code of an audio file can be uploaded.
      private String pathAudioFormat = "";  // File format, for example, WAV
      private String pathProperty = "";     // Property character string in "language_sampleRate_domain" format.
    
      private void setShortParameter(AsrCustomShortRequest request) {
    
        // Set whether to add punctuation marks. The default value is no.
        request.setAddPunc("yes");
      }
    
      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 request timeout interval. The default value is 10000 ms.
        config.setRequestTimeout(SisConstant.DEFAULT_CONNECTION_REQUEST_TIMEOUT);
        // Set the socket timeout interval. The default value is 10000 ms.
        config.setSocketTimeout(SisConstant.DEFAULT_SOCKET_TIMEOUT);
        // Set the proxy. Make sure that the proxy is available before setting it. The unencrypted proxy new ProxyHostInfo(host, port) can also be used during proxy initialization.
        // ProxyHostInfo proxy = new ProxyHostInfo(host, port, username, password);
        // config.setProxy(proxy);
        return config;
      }
    
      private void printAsrShortResponse(AsrCustomShortResponse response) {
        System.out.println("traceId=" + response.getTraceId());
        System.out.println("text=" + response.getText());
        System.out.println("score=" + response.getScore());
        System.out.println("\n");
      }
    
      /**
       * Short Sentence Recognition 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 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.
          printAsrShortResponse(response);
    
        } 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();
        // Choice 1: Sentence Transcription
        demo.shortDemo();
      }
    
    }
    
    Table 1 User information

    Parameter

    Mandatory

    Description

    AK

    Yes

    User's AK. For details about how to obtain AK and SK, see AK/SK-Based Authentication.

    SK

    Yes

    User's SK. For details about how to obtain AK and SK, see AK/SK-Based Authentication.

    Region

    Yes

    Region where SIS resides

    ProjectId

    Yes

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

    Endpoint

    No

    Endpoint. This parameter is optional. You can directly use the default value.

    Table 2 config parameters

    Parameter

    Mandatory

    Description

    SocketTimeout

    No

    Socket timeout interval (ms). The default value is 10,000 ms.

    ConnectionTimeout

    No

    Connection timeout interval (ms). The default value is 10,000 ms.

    RequestTimeout

    No

    Request timeout interval (ms). The default value is 10,000 ms.

    Proxy

    No

    Before using a proxy, ensure that the proxy is available. You are not advised to use a proxy.

    Table 3 Request parameters

    Parameter

    Mandatory

    Description

    Data

    Yes

    Base64-encoded character string of the local audio file

    AudioFormat

    Yes

    Audio format

    Property

    Yes

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

    Add_punc

    No

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

Step 3: Calling Short Sentence Recognition

Run the AsrCustomizationDemo.java file. Then you can view the returned result.
{
    "trace_id": "7f0ba401-d82d-4bfb-8ae7-600bf54ce4f6",
    "result": {
        "text": "Welcome to xx.",
        "score": 0.06588845654993515
    }
}

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