智能文档翻译

通过智能文档翻译功能,将文本翻译为中文、英文等多种语言。通过人工智能技术,可以更高效、精准、便捷地进行多种语言的翻译。

前提条件

调用方式

智能文档翻译通过对象存储(OSS)的处理参数(x-oss-process)以同步方式调用。所有请求均采用POST方法,可使用SDK或者直接调用API。

操作名称:doc/translate

参数说明

请求参数

参数

类型

是否必须

描述

language

string

需要翻译成的目标语言。取值:

  • zh_CN:中文

  • en_US:英文

  • ja_JP:日文

  • fr_FR: 法文

content

string

待翻译的文档内容,必须经过URL安全的Base64编码。

说明
  • 最大支持长度为19500字节。

  • 仅支持翻译目标语言范围内的语言。

format

string

指定返回数据的方式。取值:

  • json(默认值):普通模式,会返回一个数据包,其中包含完整的请求结果。

  • event-stream:SSE模式,会收到多个数据包,其中每次都包含全量的数据。

返回参数

参数

类型

描述

RequestId

string

当次请求的Request ID。

Output

struct

输出的结果内容。

子节点:Text, FinishReason

Text

string

本次请求的处理得到的结果内容。

父节点:Output

FinishReason

string

表明当前生成结果的现状。取值:

  • null:正在生成

  • stop:生成结束

父节点:Output

使用 SDK

智能文档翻译仅支持同步处理,以下仅列举常见SDK通过处理参数的方式使用智能文档翻译的代码示例。如需使用其他SDK使用智能文档翻译的代码示例,请参见以下常见SDK自行调整。

Java

要求使用3.17.4及以上版本的Java SDK。

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.GenericResult;
import com.aliyun.oss.model.ProcessObjectRequest;

import java.io.IOException;
import java.util.Formatter;

public class Demo {
    public static void main(String[] args) throws ClientException, com.aliyuncs.exceptions.ClientException {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 填写阿里云通用Region ID,例如cn-hangzhou。
        String region = "cn-hangzhou";
        // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 指定Bucket名称。
        String bucketName = "examplebucket";
        // 指定待翻译的文本内容。
        String content = "太阳系由太阳以及环绕其运行的天体构成,其中包括八大行星。这些行星与太阳的距离,从近到远依次是:水星、金星、地球、火星、木星、土星、天王星、海王星。";
        String encodeContent = BinaryUtil.toBase64String(content.getBytes()).replaceAll("\\+","-")
                .replaceAll("/","_").replaceAll("=","");

        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {

            StringBuilder sbStyle = new StringBuilder();
            Formatter styleFormatter = new Formatter(sbStyle);
            // 构建智能文档翻译处理指令。
            styleFormatter.format("doc/translate,language_en_US,content_%s",encodeContent);
            System.out.println(sbStyle.toString());
            ProcessObjectRequest request = new ProcessObjectRequest(bucketName, key, sbStyle.toString());
            GenericResult processResult = ossClient.processObject(request);
            String json = IOUtils.readStreamAsString(processResult.getResponse().getContent(), "UTF-8");
            processResult.getResponse().getContent().close();
            System.out.println(json);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

PHP

要求使用PHP SDK 2.7.0及以上版本。

<?php
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 
$ak = getenv('OSS_ACCESS_KEY_ID');
$sk = getenv('OSS_ACCESS_KEY_SECRET');
// 指定Bucket名称,例如examplebucket。
$bucket = 'examplebucket';
// 指定文件名称,仅作为占位符使用。使用智能文档润色时,不读取该文件的内容。
$objectKey = 'example.doc';
// 指定待翻译的文本内容。
$txt = "太阳系由太阳以及环绕其运行的天体构成,其中包括八大行星。这些行星与太阳的距离,从近到远依次是:水星、金星、地球、火星、木星、土星、天王星、海王星。";

$base64url = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($txt));
// 构建智能文档翻译处理指令。
$body = sprintf("x-oss-process=doc/translate,language_en_US,content_%s", $base64url);

$httpVerb = 'POST';
$contentMd5 = base64_encode(md5($body, true));
$contentType = '';
$date = gmdate('D, d M Y H:i:s T');
$stringToSign = $httpVerb . "\n" . $contentMd5 . "\n" . $contentType . "\n" . $date . "\n" . "/{$bucket}/{$objectKey}?x-oss-process";
$signature = base64_encode(hash_hmac('sha1', $stringToSign, $sk, true));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://{$bucket}.oss-cn-hangzhou.aliyuncs.com/{$objectKey}?x-oss-process");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Date: ' . $date,
    'Authorization: OSS ' . $ak . ':' . $signature,
    'Content-Type: ' . $contentType,
    'Content-Md5:' . $contentMd5,
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);

$response = curl_exec($ch);

$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response === false) {
    echo "Error: " . curl_error($ch);
} else {
    if ($httpcode == 200) {
        var_dump($response);
    } else {
        echo "Error: HTTP code " . $httpcode;
    }
}

Go

要求使用Go SDK 3.0.2及以上版本。

package main

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

type TextData struct {
	RequestId string `json:"RequestId"`
	Output    struct {
		Text         string `json:"Text"`
		FinishReason string `json:"FinishReason"`
	} `json:"Output"`
}

func main() {
	// 从环境变量中获取临时访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID、OSS_ACCESS_KEY_SECRET、OSS_SESSION_TOKEN。
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// 创建OSSClient实例。
	client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("cn-hangzhou"))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// 填写Bucket名称,例如examplebucket。
	bucketName := "examplebucket"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	params := make(map[string]interface{})
	params["x-oss-process"] = nil
        // 指定待翻译的文本内容。
	txt := "太阳系由太阳以及环绕其运行的天体构成,其中包括八大行星。这些行星与太阳的距离,从近到远依次是:水星、金星、地球、火星、木星、土星、天王星、海王星。"
        // 构建智能文档翻译处理指令。
	data := fmt.Sprintf("x-oss-process=doc/translate,language_en_US,content_%v", base64.URLEncoding.EncodeToString([]byte(txt)))
	response, err := bucket.Do("POST", "example.doc", params, nil, strings.NewReader(data), nil)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	defer response.Body.Close()
	jsonData, err := io.ReadAll(response.Body)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	var text TextData
	err = json.Unmarshal(jsonData, &text)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	fmt.Printf("RequestId:%v\n", text.RequestId)
	fmt.Printf("Text:%v\n", text.Output.Text)
	fmt.Printf("FinishReason:%v\n", text.Output.FinishReason)
}

使用 API

以上操作方式底层基于API实现,如果您的程序自定义要求较高,您可以直接发起REST API请求。直接发起REST API请求需要手动编写代码计算签名。关于公共请求头Authorization的计算方法,请参见签名版本4(推荐)

普通模式

一次性返回完整的翻译结果。

请求示例

  • 待处理文件:example.doc

  • 待翻译文本:“太阳系由太阳以及环绕其运行的天体构成,其中包括八大行星。这些行星与太阳的距离,从近到远依次是:水星、金星、地球、火星、木星、土星、天王星、海王星。”

  • 翻译目标语言:en_US

  • 返回结果方式:json

POST /example.doc?x-oss-process HTTP/1.1
Host: doc-demo.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: OSS4-HMAC-SHA256 Credential=LTAI********************/20250417/cn-hangzhou/oss/aliyun_v4_request,Signature=a7c3554c729d71929e0b84489addee6b2e8d5cb48595adfc51868c299c0c218e

x-oss-process=doc/translate,language_en_US,content_5aSq6Ziz57O755Sx5aSq6Ziz5Lul5Y-K546v57uV5YW26L-Q6KGM55qE5aSp5L2T5p6E5oiQ77yM5YW25Lit5YyF5ous5YWr5aSn6KGM5pif44CC6L-Z5Lqb6KGM5pif5LiO5aSq6Ziz55qE6Led56a777yM5LuO6L-R5Yiw6L-c5L6d5qyh5piv77ya5rC05pif44CB6YeR5pif44CB5Zyw55CD44CB54Gr5pif44CB5pyo5pif44CB5Zyf5pif44CB5aSp546L5pif44CB5rW3546L5pif44CC

返回示例

HTTP/1.1 200 OK
Server: AliyunOSS
Date: Thu, 10 Aug 2023 11:09:00 GMT
Content-Type: application/json;charset=UTF-8
Connection: close
Vary: Accept-Encoding
x-oss-request-id: 6597C1C04479D830303AF61D
x-oss-server-time: 2010
Content-Encoding: gzip
{
   "RequestId":"6597C1C04479D830303AF61D",
   "Output":{
       "Text":"The solar system consists of the Sun and the celestial bodies orbiting around it, including eight major planets. In order from nearest to farthest from the Sun, these planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune.",
       "FinishReason":"stop"
    }
}

SSE 模式

以流式方式分段返回翻译结果。

请求示例

  • 待处理文件:example.doc

  • 待翻译文本:“太阳系由太阳以及环绕其运行的天体构成,其中包括八大行星。这些行星与太阳的距离,从近到远依次是:水星、金星、地球、火星、木星、土星、天王星、海王星。”

  • 翻译目标语言:en_US

  • 返回结果方式:event-stream

POST /example.doc?x-oss-process HTTP/1.1
Host: doc-demo.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: OSS4-HMAC-SHA256 Credential=LTAI********************/20250417/cn-hangzhou/oss/aliyun_v4_request,Signature=a7c3554c729d71929e0b84489addee6b2e8d5cb48595adfc51868c299c0c218e

x-oss-process=doc/translate,language_en_US,format_event-stream,content_5aSq6Ziz57O755Sx5aSq6Ziz5Lul5Y-K546v57uV5YW26L-Q6KGM55qE5aSp5L2T5p6E5oiQ77yM5YW25Lit5YyF5ous5YWr5aSn6KGM5pif44CC6L-Z5Lqb6KGM5pif5LiO5aSq6Ziz55qE6Led56a777yM5LuO6L-R5Yiw6L-c5L6d5qyh5piv77ya5rC05pif44CB6YeR5pif44CB5Zyw55CD44CB54Gr5pif44CB5pyo5pif44CB5Zyf5pif44CB5aSp546L5pif44CB5rW3546L5pif44CC

返回示例

HTTP/1.1 200 OK
Server: AliyunOSS
Date: Thu, 10 Aug 2023 11:20:11 GMT
Content-Type: text/event-stream;charset=UTF-8
Transfer-Encoding: chunked
Connection: close
x-oss-request-id: 6597C2174479D83837AE0C1E
x-oss-server-time: 587

id: 0
event: Result
data: {"RequestId":"6597C2174479D83837AE0C1E","Output":{"Text":"The","FinishReason":"null"}}

id: 1
event: Result
data: {"RequestId":"6597C2174479D83837AE0C1E","Output":{"Text":"The solar system consists","FinishReason":"null"}}

id: 2
event: Result
data: {"RequestId":"6597C2174479D83837AE0C1E","Output":{"Text":"The solar system consists of the","FinishReason":"null"}}

id: 3
event: Result
data: {"RequestId":"6597C2174479D83837AE0C1E","Output":{"Text":"The solar system consists of the Sun and the","FinishReason":"null"}}

id: 4
event: Result
data: {"RequestId":"6597C2174479D83837AE0C1E","Output":{"Text":"The solar system consists of the Sun and the celestial bodies orbiting around it","FinishReason":"null"}}

id: 5
event: Result
data: {"RequestId":"6597C2174479D83837AE0C1E","Output":{"Text":"The solar system consists of the Sun and the celestial bodies orbiting around it, including eight major","FinishReason":"null"}}

id: 6
event: Result
data: {"RequestId":"6597C2174479D83837AE0C1E","Output":{"Text":"The solar system consists of the Sun and the celestial bodies orbiting around it, including eight major planets. In order of","FinishReason":"null"}}

id: 7
event: Result
data: {"RequestId":"6597C2174479D83837AE0C1E","Output":{"Text":"The solar system consists of the Sun and the celestial bodies orbiting around it, including eight major planets. In order of increasing distance from the","FinishReason":"null"}}

id: 8
event: Result
data: {"RequestId":"6597C2174479D83837AE0C1E","Output":{"Text":"The solar system consists of the Sun and the celestial bodies orbiting around it, including eight major planets. In order of increasing distance from the Sun, these planets are:","FinishReason":"null"}}

id: 9
event: Result
data: {"RequestId":"6597C2174479D83837AE0C1E","Output":{"Text":"The solar system consists of the Sun and the celestial bodies orbiting around it, including eight major planets. In order of increasing distance from the Sun, these planets are: Mercury, Venus, Earth,","FinishReason":"null"}}

id: 10
event: Result
data: {"RequestId":"6597C2174479D83837AE0C1E","Output":{"Text":"","FinishReason":"null"}}

id: 11
event: Result
data: {"RequestId":"6597C2174479D83837AE0C1E","Output":{"Text":"The solar system consists of the Sun and the celestial bodies orbiting around it, including eight major planets. In order of increasing distance from the Sun, these planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn","FinishReason":"null"}}

id: 12
event: Result
data: {"RequestId":"6597C2174479D83837AE0C1E","Output":{"Text":"The solar system consists of the Sun and the celestial bodies orbiting around it, including eight major planets. In order of increasing distance from the Sun, these planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune","FinishReason":"null"}}

id: 13
event: Result
data: {"RequestId":"6597C2174479D83837AE0C1E","Output":{"Text":"The solar system consists of the Sun and the celestial bodies orbiting around it, including eight major planets. In order of increasing distance from the Sun, these planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune.","FinishReason":"null"}}

配额与限制

  • 文档智能翻译功能仅支持同步处理(x-oss-process处理方式)。

  • 该接口需采用POST方式请求。

  • 不支持匿名访问,所有请求必须经过签名授权。