You need to enable JavaScript to run this app.
导航
文本翻译API
最近更新时间:2024.05.15 13:20:38首次发布时间:2021.02.23 10:42:10

接口描述

文本翻译是火山引擎依托领先的自然语言处理技术推出的在线文本翻译服务,支持财经、生物医药、小说网文等垂类领域翻译引擎,为客户提供精准翻译高效的文本翻译服务。

签名算法

您可在签名算法页面获得相关指引。
涉及字段:

Host = translate.volcengineapi.com
URI = /
QueryString = Action=TranslateText&Version=2020-06-01
Region = cn-north-1
Service = translate

接口限制

支持语言:可在语言支持列表中查看文本翻译支持的的源语言及目标语言。

接口说明

  • 请求方法
    POST
  • 请求体
字段类型是否为必须项说明备注
SourceLanguageString源语言若不配置此字段,则代表自动检测源语言
TargetLanguageString目标语言可在语言支持中查询对应的语言代码
TextList[String]待翻译的文本列表列表长度不超过16
总文本长度不超过5000字符
  • 返回体
字段类型说明备注
ResponseMetadataResponseMetadata通用字段
TranslationList[Translation]
  • Translation:: String
    翻译结果
  • DetectedSourceLanguage:: Maybe String
    自动检测出的源语言
DetectedSourceLanguage 仅在源语言未指定时会返回结果

在接口错误时,错误信息会在ResponseMetadata.Error中,包含了错误类型Code:: String和错误信息Message:: String两个字段,其中错误码列表为:

错误码说明解决方法
-400请求参数错误,具体错误可参考Message信息请检查请求参数是否正确
-415不支持的翻译请检查语言支持里是否支持该语向
-429请求过于频繁请降低请求频率
-500翻译服务内部错误请重试。若多次重试失败,请联系客服。
1000XX接口错误信息详见接口错误信息
  • 样例
    • 请求体
    {
        "TargetLanguage": "zh",
        "TextList": [
            "Hello world"
        ]
    }
    
    • 返回体
    {
        "TranslationList": [
            {
                "Translation": "你好世界",
                "DetectedSourceLanguage": "en"
            }
        ],
        "ResponseMetadata": {
            "RequestId": "202004092306480100140440781F5D7119",
            "Action": "TranslateText",
            "Version": "2020-06-01",
            "Service": "translate",
            "Region": "cn-north-1",
            "Error": null
        }
    }
    

示例代码

  • 使用 Python

依赖 volc-sdk-python

import json

from volcengine.ApiInfo import ApiInfo
from volcengine.Credentials import Credentials
from volcengine.ServiceInfo import ServiceInfo
from volcengine.base.Service import Service

k_access_key = '密钥管理中的 AccessKey ID' # https://console.volcengine.com/iam/keymanage/
k_secret_key = '密钥管理中的 AccessKey Secret'
k_service_info = \
    ServiceInfo('translate.volcengineapi.com',
                {'Content-Type': 'application/json'},
                Credentials(k_access_key, k_secret_key, 'translate', 'cn-north-1'),
                5,
                5)
k_query = {
    'Action': 'TranslateText',
    'Version': '2020-06-01'
}
k_api_info = {
    'translate': ApiInfo('POST', '/', k_query, {}, {})
}
service = Service(k_service_info, k_api_info)
body = {
    'TargetLanguage': 'zh',
    'TextList': ['Hello world', 'こんにちは世界'],
}
res = service.json('translate', {}, json.dumps(body))
print(json.loads(res))
  • Go
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"time"

	"github.com/volcengine/volc-sdk-golang/base"
)

const (
	kAccessKey      = "密钥管理中的 AccessKey ID" // https://console.volcengine.com/iam/keymanage/
	kSecretKey      = "密钥管理中的 AccessKey Secret"
	kServiceVersion = "2020-06-01"
)

var (
	ServiceInfo = &base.ServiceInfo{
		Timeout: 5 * time.Second,
		Host:    "translate.volcengineapi.com",
		Header: http.Header{
			"Accept": []string{"application/json"},
		},
		Credentials: base.Credentials{Region: base.RegionCnNorth1, Service: "translate"},
	}
	ApiInfoList = map[string]*base.ApiInfo{
		"TranslateText": {
			Method: http.MethodPost,
			Path:   "/",
			Query: url.Values{
				"Action":  []string{"TranslateText"},
				"Version": []string{kServiceVersion},
			},
		},
	}
)

func main() {
	client := base.NewClient(ServiceInfo, ApiInfoList)
	client.SetAccessKey(kAccessKey)
	client.SetSecretKey(kSecretKey)

	req := Req{
		SourceLanguage: "en",
		TargetLanguage: "zh",
		TextList:       []string{"hello world"},
	}
	body, _ := json.Marshal(req)

	resp, code, err := client.Json("TranslateText", nil, string(body))
	if err != nil {
		panic(err)
	}
	fmt.Printf("%d %s\n", code, string(resp))
}

type Req struct {
	SourceLanguage string   `json:"SourceLanguage"`
	TargetLanguage string   `json:"TargetLanguage"`
	TextList       []string `json:"TextList"`
}

依赖 volc-sdk-php
通过
composer require volcengine/volc-sdk-php
会安装依赖到当前目录的 vendor 目录下,在当前目录下使用运行以下脚本

<?php
require("./vendor/autoload.php");

use Volc\Base\V4Curl;

const kAccessKey = "密钥管理中的 AccessKey ID";
const kSecretKey = "密钥管理中的 AccessKey Secret";

class Translate extends V4Curl {
    protected $apiList = [
        "LangDetect" => [
            "url" => "/",
            "method" => "post",
            "config" => [
                "query" => [
                    "Action" => "LangDetect",
                    "Version" => "2020-06-01",
                ],
            ],
        ],
        "TranslateText" => [
            "url" => "/",
            "method" => "post",
            "config" => [
                "query" => [
                    "Action" => "TranslateText",
                    "Version" => "2020-06-01",
                ],
            ],
        ],
    ];

    protected function getConfig(string $region) {
        return [
            "host" => "https://translate.volcengineapi.com",
            "config" => [
                "timeout" => 5.0,
                "headers" => [
                    "Accept" => "application/json"
                ],
                "v4_credentials" => [
                    "region" => "cn-north-1",
                    "service" => "translate",
                ],
            ],
        ];
    }

    public function langDetect(array $textList): array {
        $req = array('TextList' => $textList);
        try {
            $resp = $this->request('LangDetect', ['json' => $req]);
        } catch (\Throwable $e) {
            throw $e;
        }
        if ($resp->getStatusCode() != 200) {
            throw new Exception("failed to detect language: status_code=%d, resp=%s", $resp->getStatusCode(), $resp->getBody());
        }
        return json_decode($resp->getBody()->getContents(), true)["DetectedLanguageList"];
    }

    public function translateText(string $sourceLanguage, string $targetLanguage, array $textList): array {
        $req = array('SourceLanguage' => $sourceLanguage, 'TargetLanguage' => $targetLanguage, 'TextList' => $textList);
        try {
            $resp = $this->request('TranslateText', ['json' => $req]);
        } catch (\Throwable $e) {
            throw $e;
        }
        if ($resp->getStatusCode() != 200) {
            throw new Exception("failed to translate: status_code=%d, resp=%s", $resp->getStatusCode(), $resp->getBody());
        }
        return json_decode($resp->getBody()->getContents(), true)["TranslationList"];
    }
}

$translator = Translate::getInstance();
$translator->setAccessKey(kAccessKey);
$translator->setSecretKey(kSecretKey);

var_dump($translator->langDetect(array("Hello world")));
var_dump($translator->translateText("en", "zh", array("Hello world")));
var_dump($translator->translateText("", "zh", array("Hello world")));