Todos os produtos
Search
Central de documentação

Object Storage Service:Polimento inteligente de documentos

Última atualização: Jul 03, 2026

O polimento inteligente de documentos otimiza a redação, estrutura e layout dos documentos para melhorar a clareza e legibilidade. Chame este recurso especificando o parâmetro de processamento síncrono x-oss-process=doc/polish através de um SDK ou API.

Pré-requisitos

  • Crie um projeto do Intelligent Media Management (IMM) e anexe-o ao bucket do Object Storage Service (OSS) de destino. Para mais informações, consulte Início Rápido e AttachOSSBucket.

  • Conceda as permissões necessárias à identidade que você usa para acessar o IMM.

Parâmetros

Ação: doc/polish

A tabela a seguir descreve os parâmetros.

Parâmetro

Tipo

Obrigatório

Descrição

content

string

Sim

O conteúdo que você deseja polir. O conteúdo deve ser codificado em Base64 seguro para URL.

Nota

O conteúdo pode ter até 19.500 bytes de comprimento.

format

string

Não

O modo de resposta. Valores válidos:

  • json (padrão): modo regular. Um pacote de dados que contém a resposta completa é retornado.

  • event-stream: modo Server-Sent Events (SSE). Múltiplos pacotes de dados são retornados. Cada pacote contém os dados completos.

A tabela a seguir descreve os parâmetros de resposta.

Parâmetro

Tipo

Descrição

RequestId

string

O ID da solicitação.

Output

struct

A saída.

Nós filhos: Text, FinishReason

Text

string

O conteúdo da resposta.

Nó pai: Output

FinishReason

string

O status do resultado. Valores válidos:

  • null: A tarefa está em execução.

  • stop: A tarefa terminou.

Nó pai: Output

Usar SDKs

Os exemplos a seguir mostram como usar SDKs comuns para polimento inteligente de documentos. Para outros SDKs, ajuste o código de acordo.

Java

É necessário o Java SDK 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 {
        // Defina o endpoint para o endpoint da região onde o bucket está localizado.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Especifique o ID da região da Alibaba Cloud, por exemplo, cn-hangzhou.
        String region = "cn-hangzhou";
        // Obtenha credenciais de acesso das variáveis de ambiente. Antes de executar este código, certifique-se de que as variáveis de ambiente OSS_ACCESS_KEY_ID e OSS_ACCESS_KEY_SECRET estão configuradas.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Especifique o nome do bucket.
        String bucketName = "examplebucket";
        // Especifique o nome do arquivo, que é usado apenas como um espaço reservado. Quando você usa o polimento inteligente de documentos, o conteúdo deste arquivo não é lido.
        String key ="example.docx";
        // Especifique o texto a ser polido.
        String content = "The solar system consists of the Sun and the celestial bodies that orbit it, including eight planets. In order of their distance from the Sun, from nearest to farthest, these planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune.";
        String encodeContent = BinaryUtil.toBase64String(content.getBytes()).replaceAll("\\+","-")
                .replaceAll("/","_").replaceAll("=","");

        // Crie uma instância do OSSClient.
        // Quando a instância do OSSClient não for mais usada, chame o método shutdown para liberar recursos.
        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);
            // Construa a instrução de polimento inteligente de documentos.
            styleFormatter.format("doc/polish,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

É necessário o PHP SDK 2.7.0 ou posterior.

<?php
// Obtenha credenciais de acesso das variáveis de ambiente. Antes de executar este código, certifique-se de que as variáveis de ambiente OSS_ACCESS_KEY_ID e OSS_ACCESS_KEY_SECRET estão configuradas.
$ak = getenv('OSS_ACCESS_KEY_ID');
$sk = getenv('OSS_ACCESS_KEY_SECRET');
// Especifique o nome do bucket, por exemplo, examplebucket.
$bucket = 'examplebucket';
// Especifique o nome do arquivo, que é usado apenas como um espaço reservado. Quando você usa o polimento inteligente de documentos, o conteúdo deste arquivo não é lido.
$objectKey = 'example.docx';
// Especifique o texto a ser polido.
$txt = "The solar system consists of the Sun and the celestial bodies that orbit it, including eight planets. In order of their distance from the Sun, from nearest to farthest, these planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune.";

$base64url = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($txt));
// Construa a instrução de polimento inteligente de documentos.
$body = sprintf("x-oss-process=doc/polish,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

É necessário o Go SDK 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() {
	// Obtenha credenciais de acesso temporário das variáveis de ambiente. Antes de executar este código, certifique-se de que as variáveis de ambiente OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET e OSS_SESSION_TOKEN estão configuradas.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Crie uma instância do 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)
	}

	// Especifique o nome do bucket, por exemplo, 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
        // Especifique o texto a ser polido.
	txt := "The solar system consists of the Sun and the celestial bodies that orbit it, including eight planets. In order of their distance from the Sun, from nearest to farthest, these planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune."
        // Construa a instrução de polimento inteligente de documentos.
	data := fmt.Sprintf("x-oss-process=doc/polish,content_%v", base64.URLEncoding.EncodeToString([]byte(txt)))
        // example.docx é um arquivo no bucket e é usado como um espaço reservado. Quando você usa o polimento inteligente de documentos, o conteúdo deste arquivo não é lido.
	response, err := bucket.Do("POST", "example.docx", 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)
}

Usar a API

Nota

O polimento inteligente de documentos requer um nome de arquivo, mas o nome de arquivo serve apenas como um espaço reservado. O recurso poli o valor do parâmetro content.

Modo normal

Retorna o resultado polido completo de uma só vez.

Solicitação de exemplo

  • Arquivo a ser processado: example.doc

  • Texto a ser polido: "The solar system consists of the Sun and the celestial bodies that orbit it, including eight planets. In order of their distance from the Sun, from nearest to farthest, these planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune."

  • Formato de 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/polish,content_5aSq6Ziz57O755Sx5aSq6Ziz5Lul5Y-K546v57uV5YW26L-Q6KGM55qE5aSp5L2T5p6E5oiQ77yM5YW25Lit5YyF5ous5YWr5aSn6KGM5pif44CC6L-Z5Lqb6KGM5pif5LiO5aSq6Ziz55qE6Led56a777yM5LuO6L-R5Yiw6L-c5L6d5qyh5piv77ya5rC05pif44CB6YeR5pif44CB5Zyw55CD44CB54Gr5pif44CB5pyo5pif44CB5Zyf5pif44CB5aSp546L5pif44CB5rW3546L5pif44CC

Resposta de exemplo

HTTP/1.1 200 OK
Server: AliyunOSS
Date: Thu, 10 Aug 2023 11:56:21 GMT
Content-Type: application/json;charset=UTF-8
Connection: close
Vary: Accept-Encoding
x-oss-request-id: 6597BEF94479D8313302D71D
x-oss-server-time: 2106
Content-Encoding: gzip

{
    "RequestId":"6597BEF94479D8313302D71D",
    "Output":{
        "Text":"The solar system is composed of the Sun and numerous celestial bodies that orbit it, including eight major planets. In order of their distance from the Sun, from nearest to farthest, these eight planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune.",
        "FinishReason":"stop"
    }
}

Modo SSE

Transmite o resultado polido em segmentos.

Solicitação de exemplo

  • Arquivo a ser processado: example.doc

  • Texto a ser polido: "The solar system consists of the Sun and the celestial bodies that orbit it, including eight planets. In order of their distance from the Sun, from nearest to farthest, these planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune."

  • Formato de 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/polish,format_event-stream,content_5aSq6Ziz57O755Sx5aSq6Ziz5Lul5Y-K546v57uV5YW26L-Q6KGM55qE5aSp5L2T5p6E5oiQ77yM5YW25Lit5YyF5ous5YWr5aSn6KGM5pif44CC6L-Z5Lqb6KGM5pif5LiO5aSq6Ziz55qE6Led56a777yM5LuO6L-R5Yiw6L-c5L6d5qyh5piv77ya5rC05pif44CB6YeR5pif44CB5Zyw55CD44CB54Gr5pif44CB5pyo5pif44CB5Zyf5pif44CB5aSp546L5pif44CB5rW3546L5pif44CC

Resposta de exemplo

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


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

id: 1
event: Result
data: {"RequestId":"690487C31AFF653634FED36C","Output":{"Text":"The solar","FinishReason":"null"}}

id: 2
event: Result
data: {"RequestId":"690487C31AFF653634FED36C","Output":{"Text":"The solar system is","FinishReason":"null"}}

id: 3
event: Result
data: {"RequestId":"690487C31AFF653634FED36C","Output":{"Text":"The solar system is composed of the","FinishReason":"null"}}

id: 4
event: Result
data: {"RequestId":"690487C31AFF653634FED36C","Output":{"Text":"The solar system is composed of the Sun and numerous celestial","FinishReason":"null"}}

id: 5
event: Result
data: {"RequestId":"690487C31AFF653634FED36C","Output":{"Text":"The solar system is composed of the Sun and numerous celestial bodies that orbit it, including","FinishReason":"null"}}

id: 6
event: Result
data: {"RequestId":"690487C31AFF653634FED36C","Output":{"Text":"The solar system is composed of the Sun and numerous celestial bodies that orbit it, including eight major planets. In order","FinishReason":"null"}}

id: 7
event: Result
data: {"RequestId":"690487C31AFF653634FED36C","Output":{"Text":"The solar system is composed of the Sun and numerous celestial bodies that orbit it, including eight major planets. In order of their distance from the Sun, from nearest","FinishReason":"null"}}

id: 8
event: Result
data: {"RequestId":"690487C31AFF653634FED36C","Output":{"Text":"The solar system is composed of the Sun and numerous celestial bodies that orbit it, including eight major planets. In order of their distance from the Sun, from nearest to farthest, these","FinishReason":"null"}}

id: 9
event: Result
data: {"RequestId":"690487C31AFF653634FED36C","Output":{"Text":"The solar system is composed of the Sun and numerous celestial bodies that orbit it, including eight major planets. In order of their distance from the Sun, from nearest to farthest, these eight planets are:","FinishReason":"null"}}

id: 10
event: Result
data: {"RequestId":"690487C31AFF653634FED36C","Output":{"Text":"The solar system is composed of the Sun and numerous celestial bodies that orbit it, including eight major planets. In order of their distance from the Sun, from nearest to farthest, these eight planets are: Mercury, Venus,","FinishReason":"null"}}

id: 11
event: Result
data: {"RequestId":"690487C31AFF653634FED36C","Output":{"Text":"The solar system is composed of the Sun and numerous celestial bodies that orbit it, including eight major planets. In order of their distance from the Sun, from nearest to farthest, these eight planets are: Mercury, Venus, Earth, Mars, Jupiter,","FinishReason":"null"}}

id: 12
event: Result
data: {"RequestId":"690487C31AFF653634FED36C","Output":{"Text":"The solar system is composed of the Sun and numerous celestial bodies that orbit it, including eight major planets. In order of their distance from the Sun, from nearest to farthest, these eight planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Ura","FinishReason":"null"}}

id: 13
event: Result
data: {"RequestId":"690487C31AFF653634FED36C","Output":{"Text":"The solar system is composed of the Sun and numerous celestial bodies that orbit it, including eight major planets. In order of their distance from the Sun, from nearest to farthest, these eight planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune","FinishReason":"null"}}

id: 14
event: Result
data: {"RequestId":"690487C31AFF653634FED36C","Output":{"Text":"The solar system is composed of the Sun and numerous celestial bodies that orbit it, including eight major planets. In order of their distance from the Sun, from nearest to farthest, these eight planets are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune.","FinishReason":"stop"}}

Cotas e limites

  • O polimento inteligente de documentos suporta apenas processamento síncrono (x-oss-process).

  • Você deve usar o método POST para enviar solicitações.

  • O acesso anônimo não é suportado. Todas as solicitações devem ser assinadas e autorizadas.