Traduci testo

Richiedere una traduzione del testo rispetto a un modello.

Esempio di codice

Go

Per scoprire come installare e utilizzare la libreria client per AutoML Translation, consulta la pagina relativa alle librerie client di AutoML Translation. Per saperne di più, consulta la documentazione di riferimento dell'API AutoML Translation Go.

Per eseguire l'autenticazione in AutoML Translation, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta la pagina Configurare l'autenticazione per un ambiente di sviluppo locale.

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// translatePredict does a prediction for translate.
func translatePredict(w io.Writer, projectID string, location string, modelID string, content string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// modelID := "TRL123456789..."
	// content := "text to translate"

	ctx := context.Background()
	client, err := automl.NewPredictionClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPredictionClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.PredictRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
		Payload: &automlpb.ExamplePayload{
			Payload: &automlpb.ExamplePayload_TextSnippet{
				TextSnippet: &automlpb.TextSnippet{
					Content:  content,
					MimeType: "text/plain", // Types: "text/plain", "text/html"
				},
			},
		},
	}

	resp, err := client.Predict(ctx, req)
	if err != nil {
		return fmt.Errorf("Predict: %w", err)
	}

	for _, payload := range resp.GetPayload() {
		fmt.Fprintf(w, "Translated content: %v\n", payload.GetTranslation().GetTranslatedContent().GetContent())
	}

	return nil
}

Java

Per scoprire come installare e utilizzare la libreria client per AutoML Translation, consulta la pagina relativa alle librerie client di AutoML Translation. Per saperne di più, consulta la documentazione di riferimento dell'API AutoML Translation Java.

Per eseguire l'autenticazione in AutoML Translation, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta la pagina Configurare l'autenticazione per un ambiente di sviluppo locale.

import com.google.cloud.automl.v1.ExamplePayload;
import com.google.cloud.automl.v1.ModelName;
import com.google.cloud.automl.v1.PredictRequest;
import com.google.cloud.automl.v1.PredictResponse;
import com.google.cloud.automl.v1.PredictionServiceClient;
import com.google.cloud.automl.v1.TextSnippet;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

class TranslatePredict {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String filePath = "path_to_local_file.txt";
    predict(projectId, modelId, filePath);
  }

  static void predict(String projectId, String modelId, String filePath) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (PredictionServiceClient client = PredictionServiceClient.create()) {
      // Get the full path of the model.
      ModelName name = ModelName.of(projectId, "us-central1", modelId);

      String content = new String(Files.readAllBytes(Paths.get(filePath)));

      TextSnippet textSnippet = TextSnippet.newBuilder().setContent(content).build();
      ExamplePayload payload = ExamplePayload.newBuilder().setTextSnippet(textSnippet).build();
      PredictRequest predictRequest =
          PredictRequest.newBuilder().setName(name.toString()).setPayload(payload).build();

      PredictResponse response = client.predict(predictRequest);
      TextSnippet translatedContent =
          response.getPayload(0).getTranslation().getTranslatedContent();
      System.out.format("Translated Content: %s\n", translatedContent.getContent());
    }
  }
}

Node.js

Per scoprire come installare e utilizzare la libreria client per AutoML Translation, consulta la pagina relativa alle librerie client di AutoML Translation. Per saperne di più, consulta la documentazione di riferimento dell'API AutoML Translation Node.js.

Per eseguire l'autenticazione in AutoML Translation, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta la pagina Configurare l'autenticazione per un ambiente di sviluppo locale.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const modelId = 'YOUR_MODEL_ID';
// const filePath = 'path_to_local_file.txt';

// Imports the Google Cloud AutoML library
const {PredictionServiceClient} = require('@google-cloud/automl').v1;
const fs = require('fs');

// Instantiates a client
const client = new PredictionServiceClient();

// Read the file content for translation.
const content = fs.readFileSync(filePath, 'utf8');

async function predict() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
    payload: {
      textSnippet: {
        content: content,
      },
    },
  };

  const [response] = await client.predict(request);

  console.log(
    'Translated content: ',
    response.payload[0].translation.translatedContent.content
  );
}

predict();

Python

Per scoprire come installare e utilizzare la libreria client per AutoML Translation, consulta la pagina relativa alle librerie client di AutoML Translation. Per saperne di più, consulta la documentazione di riferimento dell'API AutoML Translation Python.

Per eseguire l'autenticazione in AutoML Translation, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta la pagina Configurare l'autenticazione per un ambiente di sviluppo locale.

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# model_id = "YOUR_MODEL_ID"
# file_path = "path_to_local_file.txt"

prediction_client = automl.PredictionServiceClient()

# Get the full path of the model.
model_full_id = automl.AutoMlClient.model_path(project_id, "us-central1", model_id)

# Read the file content for translation.
with open(file_path, "rb") as content_file:
    content = content_file.read()
content.decode("utf-8")

text_snippet = automl.TextSnippet(content=content)
payload = automl.ExamplePayload(text_snippet=text_snippet)

response = prediction_client.predict(name=model_full_id, payload=payload)
translated_content = response.payload[0].translation.translated_content

print(f"Translated content: {translated_content.content}")

Passaggi successivi

Per cercare e filtrare esempi di codice per altri prodotti Google Cloud, consulta il browser di esempio Google Cloud.