API Document for Machine Translation

Description of the Interface

Machine Translation, based on the machine translation engine independently developed by iFLYTEK, has been able to support more than 10 languages like English, Japanese, French, Spanish and Russian (including Uighur and Tibetan which are supported but not externally available at present), presenting a high translation quality. It has been applied on the iFLYTEK Translator, and achieved excellent results. Please refer to[List of Languages](#List of Languages) for details. By calling this interface, the text in source language can be converted into the text in target language.
This function provides developers with a common interface through HTTP API. HTTP API is applicable to AI service scenarios with primary interactive data transmission. Compared with SDK, API is featured as light weight and cross-language. In addition, note that the HTTP API protocol used for this interface does not support cross-domain.

Currently only Coversion between Simplified Chinese and Japanese, Korean, Vietnamese, Thai are supported in Machine Translation Beta Version. Please stay tuned.

Interface Demos

Interface Demos Please click here download demos
At present, only the demos for some development languages are provided. For other languages, please carry out the development referring to the interface document below.

Requirements for the Interface

The following requirements should be met if the machine translation is integrated.

Content Description
Transmission Mode http[s] (https is strongly recommended for improving the security)
Request URL http[s]: //its-api-sg.xf-yun.com/v2/its
Note: The server IP is not fixed. To ensure the stability of your interface, please call the interface by using the domain name instead of by specifying the IP.
Request Line POST /v2/its HTTP/1.1
Interface Authentication Signature mechanism, refer to[Interface Authentication](#Interface Authentication)
Character Encoding UTF-8
Response Format Unified JSON format
Development Language Any language which allows to make HTTP requests for iFLYTEK cloud services.
Scope of Application Any operating system except browsers for which the interface should be called through the backend because cross-domain is not supported.
Text Length The length of a single text should not exceed 256 characters.
Each of a Chinese character, an English letter, a punctuation mark, etc. is counted as one character.
Text Size The size after base64-encoded should not exceed 1024 bytes (about 256 Chinese characters)
Text Language Supports more than 10 languages. Refer to [List of Languages](#List of Languages)for details.

Interface Calling Flow

  • Calculate the signature based on hamc-sha256 through the interface key, and put the signature and other parameters in HTTP Request Header. Refer to [Interface Authentication](#Interface Authentication) below for details.
  • Put the request parameters and image data in Http Request Body and submit them in POST form. Refer to [Request Parameters](#Request Parameters)below for details.
  • Receive the result returned from the server-side after the HTTP request is sent to the server-side.

Whitelist

The IP whitelist is disabled by default, which means this service does not restrict from calling IP.
When calling this business interface:

  • If the IP whitelist is disabled, the IP is considered as unrestricted for the interface, and it will not be checked.
  • If the IP whitelist is enabled, the server-side will check whether the caller’s IP is included in the IP whitelist configured by the iFLYTEK Open Platform. For the requests from IPs that are not configured in the whitelist, the server-side will reject to provide the service.

Rules for IP Whitelist

  • Perform edit at console-IP whitelist for the corresponding service, and the edited content will become valid about five minutes after saved.
  • The IP whitelists should be set separately for different services of different APPIDs.
  • The IP whitelist should be set to WAN IP instead of LAN IP.
  • If {"message":"Your IP address is not allowed"} is returned during the handshake phase, it indicates that the server-side refuses to provide the service because the IP whitelist is set incorrectly or is still invalid.

Authentication

When calling the business interface, the HTTP request must be signed, and the server-side identifies the user through the signature and authenticates its legality.

Authentication Method

在Http Request Configure the following authentication parameters in HTTP Request Header for the authentication of authorization, where the signature information is put in the request header’s Authorization.
Example of request header:

    Content-Type:application/json
    Accept:application/json,version=1.0
    Host:itrans.xfyun.cn
    Date:Wed, 20 Nov 2019 03:14:25 GMT
    Digest:SHA-256=2iwDpX6yAoQAeeAhT4yi3Tx9XRaWvAAvn3L8Ip6fdpA=
    Authorization:api_key="your_key", algorithm="hmac-sha256", headers="host date request-line digest", signature="$signature"

Authentication Parameters:

Parameter Type Required Description Example
Host string Yes Request host itrans.xfyun.cn
Date string Yes Current timestamp, in RFC1123 format ("EEE, dd MMM yyyy HH:mm:ss z") Wed, 20 Nov 2019 03:14:25 GMT
Digest string Yes Encrypted request body
SHA-256=Base64(SHA256(request body))
Refer to [Request Parameters](#Request Parameters)
SHA-256=2iwDpX6....
Authorization string Yes Information related to the signature encoded with base64 (the signature is based on hamc-sha256 calculation.) Refer to the content below
  • Date parameter generation rules:

Date must be based on UTC+0 or GMT time zone, in RFC1123 format (Wed, 20 Nov 2019 03:14:25 GMT). The server-side will check the clock skew for the Date, allowing the maximum deviation of 300 seconds. Once such value is exceeded, the request will be rejected.

  • Authorization parameter generation format:
    Authorization: api_key="your_key", algorithm="hmac-sha256", headers="host date request-line digest", signature="$signature"
    Example:Authorization: api_key="apikeyXXXXXXXXXXXXXXXXXXXXXXXXXX", algorithm="hmac-sha256", headers="host date request-line digest", signature="XwMFU8JKrxdDeVLpplLua9Rjcv/IlaS5tWbmXg0eM80="

Where, api_key is the APIKey obtained in the console (which is a 32-bit string, and can be viewed on the machine translation page of the console), api_key="apikeyXXXXXXXXXXXXXXXXXXXXXXXXXX” is taken as an example here.
Algorithm is an encryption algorithm (supports hmac-sha256 only), and headers are the parameters involved in signature.
Signature is a string which is base64-encoded after using the encryption algorithm to sign the parameters participating in signature, see below for details.

  • • Signature parameter generation rules:

The signature’ original field is composed of four parameters: host, date, request-line and digest which are concatenated in a certain format.
The concatenation format is (\n is a new line character, ’:’ is followed by a space): host: $host\ndate: $date\n $request-line\ndigest: $digest

For example, if the requesting url is “https://its-api-sg.xf-yun.com/v2/its<br>”<br>
The requesting body should be: {"common":{"app_id":"5dXXXXXX"},"business":{"from":"cn","to":"en"},"data":{"text":"5Lit5Y2O5Lq65rCR5YWx5ZKM5Zu95LqOMTk0OeW5tOaIkOeriw=="}}

Then, the steps to generate signature are as follows:

1)Perform SHA256 calculation on body, write the string obtained after the calculation result is Base64-encoded behind "SHA-256=", which is namely the value of the field “digest”.

    digest: SHA-256=Base64(SHA256(请求body))
    Example:digest: SHA-256=2iwDpX6yAoQAeeAhT4yi3Tx9XRaWvAAvn3L8Ip6fdpA=

2)Construct the original field of signature (signature_origin)

    host: itrans.xfyun.cn
    date: Wed, 20 Nov 2019 03:14:25 GMT
    POST /v2/its HTTP/1.1
    digest: SHA-256=2iwDpX6yAoQAeeAhT4yi3Tx9XRaWvAAvn3L8Ip6fdpA=

3)Sign the “signature_origin” using hmac-sha256 algorithm in combination with apiSecret. The signed summary “signature_sha apiSecret” can be viewed in the machine translation page of the console. “apisecretXXXXXXXXXXXXXXXXXXXXXXX” is taken as an example here.

    signature_sha=hmac-sha256(signature_origin,$apiSecret)

4)Encode “signature_sha” with base64, to obtain the final signature.

    signature=base64(signature_sha)
    Example:d4kHthlsRTE/YAjFnuJiNs1u/cXOmSI4fAvKwLawQ+8=

Examples of Authentication (golang)

    package main
    import (
        "crypto/hmac"
        "crypto/sha256"
        "encoding/base64"
        "fmt"
        "time"
        "github.com/valyala/fasthttp"
    )
    const (
        // Supported algorithm
        Algorithm = "hmac-sha256"
        // Version protocol
        HttpProto = "HTTP/1.1"
        // Supposed secret
        Secret = "12345"
    )
    func assemblyRequestHeader(req *fasthttp.Request, apiKey, host, uri string, body []byte) {
        req.Header.Set("Content-Type", "application/json")
        // Set the request header, where, Host Date must have:
        req.Header.Set("Host", host)
        // date must be based on utc time zone, and the deviation between it and the service time  should not exceed 300s
        currentTime := time.Now().UTC().Format(time.RFC1123)
        req.Header.Set("Date", currentTime)
        // Perform  sha256 signature on body to generate digest header. body must be authenticated for POST requests.
        digest := "SHA-256=" + signBody(body)
        req.Header.Set("Digest", digest)
        // Signature is generated according to the content of request header.
        sign := generateSignature(host, currentTime,"POST", uri, HttpProto, digest,Secret)
        // Assemble Authorization header
        authHeader := fmt.Sprintf(`api_key="%s", algorithm="%s", headers="host date request-line digest", signature="%s"`, apiKey, Algorithm, sign)
        req.Header.Set("Authorization", authHeader)
    }
    func generateSignature(host, date, httpMethod, requestUri, httpProto, digest string, secret string) string {
        // If it is not request-line, the  header name should be followed by ASCII colon: and ASCII space, and header value
        var signatureStr string
        if len(host) != 0 {
            signatureStr = "host: " + host + "\n"
        }
        signatureStr += "date: " + date + "\n"
        // If it is request-line, use  http_method request_uri http_proto
        signatureStr += httpMethod + " " + requestUri + " " + httpProto + "\n"
        signatureStr += "digest: " + digest
        return hmacsign(signatureStr, secret)
    }
    func hmacsign(data, secret string) string {
        mac := hmac.New(sha256.New, []byte(secret))
        mac.Write([]byte(data))
        encodeData := mac.Sum(nil)
        return base64.StdEncoding.EncodeToString(encodeData)
    }
    func signBody(data []byte) string {
        // Perform sha256 signature
        sha := sha256.New()
        sha.Write(data)
        encodeData := sha.Sum(nil)
        // Through base64 conversion
        return base64.StdEncoding.EncodeToString(encodeData)
    }

Authentication Results

If the authentication is successful, an HTTP 200 status code will be returned, indicating that the protocol upgrade is successful; if the authentication fails, different HTTP Code status codes will be returned, depending on the type of errors, along with error messages. See the detailed description of errors in the table below.

HTTP Code Description Error Message Solution
401 Request parameters of authorization are not available {“message”:”Unauthorized”} Check if authorization parameters are available. Refer to [Detailed Rules for Generation of Authorization Parameters](#Authorization Parameters)
401 The resolution of signature parameters fails. {“message”:”HMAC signature cannot be verified”} Check if all signature parameters are available and correct, and if the copied api_key is correct.
401 The signature authentication fails. {“message”:”HMAC signature does not match”} There are many possible reasons for failure of signature authentication.
1. Check if api_key and api_secret are correct.
2. Check whether the parameters, i.e. host, date and request-line for calculation of signature are concatenated according to protocol requirements.
3. Check if the base64 length of signature is normal (normally 44 bytes).
403 The authentication of clock skew fails. {“message”:”HMAC signature cannot be verified, a valid date or x-date header is required for HMAC Authentication”} Check if the server time is standard. This error is reported when the deviation is more than 5 minutes.

Example of returned messages upon failure of authentication:

    HTTP/1.1 401 Forbidden
    Date: Wed, 20 Nov 2019 03:14:25 GMT
    Content-Length: 116
    Content-Type: text/plain; charset=utf-8
    {
        "message": "HMAC signature does not match"
    }

Request Parameters

When calling the business interface, it is required to configure the following parameters in HTTP Request Body, and all the request data is json string.

Parameter Name Type Required Description
common object Yes Used to upload common parameters
common.app_id string Yes APPID information applied from the platform
business object Yes Used to upload business parameters
business.from string Yes Source language
business.to string Yes Target language
data object Yes Used to upload text to be translated
data.text bytes Yes Text data, UTF-8 character set, base64-encoded
The size is required not to be more than 1024 bytes after encoding (about 256 Chinese characters).
Note: The size will be increased by about 1/3 after base64-encoded.

Examples of request parameters:

    {
        "common":{
            "app_id":"xxxxxxxx"
        },
        "business":{
            "from":"cn",
            "to" :"en"
        },
        "data":{
            "text":"5LuK5aSp5aSp5rCU5oCO5LmI5qC377yf"
        }
    }

Returned Parameters

Parameter Name Type Description
sid string Current session id
code int Returned code, 0 means success, and any other code means failure. Refer to[Error Codes](#Error Codes)for details.
message string Description message
data object Translation result. See the following for details.
If an interface error is reported (the code is not 0), this field will not be available.

The translation result is in the “result” field of the “data” field.
The “result” field contains the following information:

Parameter Type Description
from string Source language
to string Target language
trans_result object Translation result
trans_result.src string Source text
trans_result.dst string Target text

Example of returned parameters:

{
  "code": 0,
  "message": "success",
  "sid": "its....",
  "data": {
    "result": {
      "from": "cn",
      "to": "en",
      "trans_result": {
        "dst": "Hello World ",
        "src": "你好世界"
      }
    }
  }
}

Error Codes

HTTP Code Description Error Message
10106 Invalid message content ErrorContentInvalid
10700 Engine connection failed ErrorConnectFail

List of Languages

Translation between Chinese and other languages:

Language Parameter
Mandarin Chinese cn
English en
Cantonese yue
Japanese ja
Russian ru
French fr
Arabic ar
Hindi cnhi、hicn
Korea cnko、kocn
Thailand cnth、thcn
Vietnamese cnvi、vicn
Chinese Mixed Translation
Mixed Supported Languages: Afrikaans (af), Amharic (am), Catalan (ca), Danish (da), Icelandic (is),
Javanese (jv), Lithuanian (lt), Latvian (lv), Malayalam (lv), Chinese-Thai (lv), Chinese-Vietnamese (cv).(jv), Lithuanian (lt), Latvian (lv), Malayalam (ml), Marathi (mr), Bokmål Norwegian (nb), Selvian (sr),
Icelandic (sr)
(sr), Sundanese (su), Tajik (tg), Turkmen (tk).
cnxx、xxcn

Translation between English and other languages:

Language Parameter
Arabic enar、aren
German ende、deen
Spanish enes、esen
French enfr、fren
Indonesian enid、iden
Japanese enja、jaen
Korean enko、koen

Demos

Machine translation demo java

Machine translation demo python3

Machine translation demo go

Machine translation demo nodejs

Machine translation demo C#

Q&A

What are the main functions of machine translation?

Answer: It supports the text-to-text machine translation.

What application platforms does machine translation support?

Answer: It only supports the WebAPI interface at present.

Contributing to the Documentation

Is something missing/incorrect? Please let us know by contacting openplatform@iflytek.com. If you know how to fix it straight away, don’t hesitate to create a request to help us improve our document.