通過智能文檔翻譯功能,將文本翻譯為中文、英文等多種語言。通過人工智慧技術,可以更高效、精準、便捷地進行多種語言的翻譯。
前提條件
已建立 IMM Project 並將其與目標Object Storage Service桶(Bucket)綁定。關於控制台和API如何綁定,請參見快速入門和AttachOSSBucket - 綁定Object Storage Service桶。
已為訪問身份授予 IMM 服務的相關許可權。
調用方式
智能文檔翻譯通過Object Storage Service的處理參數(x-oss-process)以同步方式調用。所有請求均採用POST方法,可使用SDK或者直接調用API。
操作名稱:doc/translate
參數說明
請求參數
參數 | 類型 | 是否必須 | 描述 |
language | string | 是 | 需要翻譯成的目標語言。取值:
|
content | string | 是 | 待翻譯的文檔內容,必須經過URL安全的Base64編碼。 說明
|
format | string | 否 | 指定返回資料的方式。取值:
|
返回參數
參數 | 類型 | 描述 |
RequestId | string | 當次請求的Request ID。 |
Output | struct | 輸出的結果內容。 子節點:Text, FinishReason |
Text | string | 本次請求的處理得到的結果內容。 父節點:Output |
FinishReason | string | 表明當前產生結果的現狀。取值:
父節點: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方式請求。
不支援匿名訪問,所有請求必須經過簽名授權。