Come utilizzare Cloud Translation - Basic (v2) per tradurre testo (2023)

Cloud Translation - Basic (v2) è un servizio di traduzione di testo offerto da Google Cloud. Questo servizio consente di tradurre testo semplice o HTML in diverse lingue. Prima di utilizzare l'API di Cloud Translation, è necessario avere un progetto abilitato per l'API e le credenziali appropriate. È anche possibile installare librerie client per vari linguaggi di programmazione per facilitare le chiamate all'API.

Richiesta di traduzione tramite l'endpoint

Per richiedere una traduzione di testo tramite l'endpoint , è necessario inviare una richiesta POST e fornire un corpo JSON che identifichi la lingua di destinazione (target) e il testo da tradurre (q). È possibile fornire più segmenti di testo da tradurre includendo più campi q o una lista di valori per il campo q. È importante specificare le lingue di destinazione utilizzando i loro codici ISO-639.

Ecco un esempio di richiesta POST utilizzando curl o PowerShell:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: PROJECT_NUMBER_OR_ID" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://translation.googleapis.com/language/translate/v2"
$cred = gcloud auth print-access-token
$headers = @{
    "Authorization" = "Bearer $cred"
    "x-goog-user-project" = "PROJECT_NUMBER_OR_ID"
}
Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://translation.googleapis.com/language/translate/v2" | Select-Object -Expand Content

La risposta sarà un JSON simile al seguente:

{
    "data": {
        "translations": [
            {
                "translatedText": "Ciao mondo",
                "detectedSourceLanguage": "it"
            },
            {
                "translatedText": "Il mio nome è Jeff",
                "detectedSourceLanguage": "it"
            }
        ]
    }
}

L'array "translations" contiene due campi "translatedText" con le traduzioni fornite nella lingua di destinazione richiesta (de: tedesco). Le traduzioni sono elencate nello stesso ordine dell'array di origine corrispondente nella richiesta.

Esempi di utilizzo dell'API di Cloud Translation in diversi linguaggi di programmazione

Go
import (
    "context"
    "fmt"
    "cloud.google.com/go/translate"
    "golang.org/x/text/language"
)

func translateText(targetLanguage, text string) (string, error) {
    ctx := context.Background()
    lang, err := language.Parse(targetLanguage)
    if err != nil {
        return "", fmt.Errorf("language.Parse: %w", err)
    }
    client, err := translate.NewClient(ctx)
    if err != nil {
        return "", err
    }
    defer client.Close()
    resp, err := client.Translate(ctx, []string{text}, lang, nil)
    if err != nil {
        return "", fmt.Errorf("Translate: %w", err)
    }
    if len(resp) == 0 {
        return "", fmt.Errorf("Translate returned empty response to text: %s", text)
    }
    return resp[0].Text, nil
}
Java
// Import the required libraries
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;

// Create an instance of the translation service
Translate translate = TranslateOptions.getDefaultInstance().getService();

// Translate the text
Translation translation = translate.translate("Ciao mondo!", Translate.TranslateOption.targetLanguage("de"));
System.out.printf("Testo tradotto:\n\t%s\n", translation.getTranslatedText());
Node.js
// Import the required libraries
const {Translate} = require('@google-cloud/translate').v2;

// Create a client
const translate = new Translate();

// Define the text and target language
const text = 'Ciao mondo!';
const target = 'de';

// Translate the text
async function translateText() {
    const [translations] = await translate.translate(text, target);
    console.log('Traduzioni:');
    translations.forEach((translation, i) => {
        console.log(`${text[i]} => (${target}) ${translation}`);
    });
}

translateText();
Python
# Import the required libraries
from google.cloud import translate_v2 as translate

# Create a client
translate_client = translate.Client()

# Define the text and target language
text = 'Ciao mondo!'
target = 'de'

# Translate the text
result = translate_client.translate(text, target_language=target)

# Print the translation
print("Testo: {}".format(result["input"]))
print("Traduzione: {}".format(result["translatedText"]))
print("Lingua di origine rilevata: {}".format(result["detectedSourceLanguage"]))

Questi sono solo alcuni esempi di come utilizzare l'API di Cloud Translation per tradurre testo in diverse lingue utilizzando vari linguaggi di programmazione. È possibile adattare il codice alle proprie esigenze specifiche.

Conclusioni

Cloud Translation - Basic (v2) è uno strumento potente per tradurre testo in diverse lingue. Utilizzando l'API di Cloud Translation, è possibile tradurre testo semplice o HTML in modo efficiente e accurato. Speriamo che queste informazioni ti siano state utili per comprendere come utilizzare Cloud Translation - Basic (v2) per le tue esigenze di traduzione.

References

Top Articles
Latest Posts
Article information

Author: Sen. Ignacio Ratke

Last Updated: 03/01/2024

Views: 6201

Rating: 4.6 / 5 (56 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Sen. Ignacio Ratke

Birthday: 1999-05-27

Address: Apt. 171 8116 Bailey Via, Roberthaven, GA 58289

Phone: +2585395768220

Job: Lead Liaison

Hobby: Lockpicking, LARPing, Lego building, Lapidary, Macrame, Book restoration, Bodybuilding

Introduction: My name is Sen. Ignacio Ratke, I am a adventurous, zealous, outstanding, agreeable, precious, excited, gifted person who loves writing and wants to share my knowledge and understanding with you.