Use o recurso de tradução inteligente de documentos para traduzir textos em vários idiomas, como chinês e inglês. Esse recurso utiliza inteligência artificial (IA) para oferecer traduções eficientes, precisas e práticas.
Pré-requisitos
Crie um projeto IMM e anexe-o a um bucket de destino do Object Storage Service (OSS). Para mais informações, consulte Primeiros passos e AttachOSSBucket.
Conceda as permissões necessárias do IMM à sua identidade de acesso. Para mais informações, consulte Permissões.
Método
O recurso de tradução inteligente de documentos é chamado de forma síncrona usando o parâmetro de processamento do Object Storage Service (OSS) x-oss-process. Envie todas as requisições com o método POST. Use um kit de desenvolvimento de software (SDK) ou chame a API diretamente.
Ação: doc/translate
Parâmetros
Parâmetros da requisição
Parâmetro | Tipo | Obrigatório | Descrição |
language | string | Sim | Idioma de destino da tradução. Valores válidos:
|
content | string | Sim | Conteúdo do documento a ser traduzido. O conteúdo deve estar codificado em Base64 seguro para URL. Nota
|
format | string | Não | Método de retorno dos dados. Valores válidos:
|
Parâmetros da resposta
Parâmetro | Tipo | Descrição |
RequestId | string | ID da requisição. |
Output | struct | Conteúdo de saída. Nós filhos: Text e FinishReason |
Text | string | Resultado da requisição. Nó pai: Output |
FinishReason | string | Status da geração do resultado. Valores válidos:
Nó pai: Output |
Uso de SDKs
O recurso de tradução inteligente de documentos suporta apenas processamento síncrono. As seções a seguir apresentam exemplos de código que demonstram como usar SDKs comuns para chamar esse recurso por meio de parâmetros de processamento. Para usar outros SDKs, adapte o código com base nos exemplos abaixo.
Java
Use o OSS SDK for Java versão 3.17.4 ou posterior.
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 {
// Set yourEndpoint to the endpoint of the region where the bucket is located.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the general-purpose region ID of Alibaba Cloud, for example, cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the bucket name.
String bucketName = "examplebucket";
// Specify the text to translate.
String content = "The solar system consists of the Sun and the celestial bodies that orbit it, including the eight planets. From nearest to farthest from the Sun, these planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune.";
String encodeContent = BinaryUtil.toBase64String(content.getBytes()).replaceAll("\\+","-")
.replaceAll("/","_").replaceAll("=","");
// Create an OSSClient instance.
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);
// Construct the processing instruction for intelligent document translation.
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
Use o OSS SDK for PHP versão 2.7.0 ou posterior.
<?php
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$ak = getenv('OSS_ACCESS_KEY_ID');
$sk = getenv('OSS_ACCESS_KEY_SECRET');
// Specify the bucket name, for example, examplebucket.
$bucket = 'examplebucket';
// Specify the file name. This is used only as a placeholder. The content of this file is not read during intelligent document translation.
$objectKey = 'example.doc';
// Specify the text to translate.
$txt = "The solar system consists of the Sun and the celestial bodies that orbit it, including the eight planets. From nearest to farthest from the Sun, these planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune.";
$base64url = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($txt));
// Construct the processing instruction for intelligent document translation.
$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
Use o OSS SDK for Go versão 3.0.2 ou posterior.
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() {
// Obtain temporary access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are set.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
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)
}
// Specify the bucket name, for example, 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
// Specify the text to translate.
txt := "The solar system consists of the Sun and the celestial bodies that orbit it, including the eight planets. From nearest to farthest from the Sun, these planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune."
// Construct the processing instruction for intelligent document translation.
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)
}
Uso da API
As operações anteriores baseiam-se em APIs. Caso seu programa exija alto nível de personalização, envie requisições REST API diretamente. Para isso, escreva manualmente o código para calcular a assinatura. Para mais informações sobre como calcular o valor do cabeçalho de requisição comum Authorization, consulte Assinatura V4 (recomendado).
Modo NAT
Este modo retorna o resultado completo da tradução de uma só vez.
Exemplo de requisição
Arquivo a processar: example.doc
Texto a traduzir: "The solar system consists of the Sun and the celestial bodies that orbit it, including the eight planets. From nearest to farthest from the Sun, these planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune."
Idioma de destino: en_US
Formato da resposta: 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
Exemplo de resposta
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"
}
}
Modo SSE
Este modo retorna o resultado da tradução em segmentos, na forma de fluxo.
Exemplo de requisição
Arquivo a processar: example.doc
Texto a traduzir: "The solar system consists of the Sun and the celestial bodies that orbit it, including the eight planets. From nearest to farthest from the Sun, these planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune."
Idioma de destino: en_US
Formato da resposta: 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
Exemplo de resposta
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"}}
id: 14
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":"stop"}}
Cotas e limites
O recurso de tradução inteligente de documentos suporta apenas processamento síncrono por meio do parâmetro x-oss-process.
Envie as requisições com o método POST.
Não há suporte para acesso anônimo. Todas as requisições exigem assinatura e autorização.