Google Cloud Translation

Typed interface to call the Google Cloud Translation v3 gRPC API to translate and detect the language of text.

Introduction

Google Cloud Translation translates text between languages and can detect the source language automatically. The gRPC API is exposed through the google.cloud.translation.v3.TranslationService service, reached at translate.googleapis.com:443 over TLS, with the main methods TranslateText, DetectLanguage and GetSupportedLanguages.

Requests are built with TsgcGRPCTranslationTranslateTextRequest, which sets Parent (projects/<id>/locations/global), Contents, SourceLanguageCode and TargetLanguageCode. The reply is returned in TsgcGRPCTranslationTranslateTextResponse, whose Translations contain the TranslatedText.

The example below authenticates with a service-account JWT, wires a TsgcGRPCClient over a TsgcHTTP2Client to the Translation host, sets the authorization Bearer metadata and calls TranslateText to translate "Hello, world!" from en to es:


    oHTTP2 := TsgcHTTP2Client.Create(nil);
    oHTTP2.Host := 'translate.googleapis.com';
    oHTTP2.Port := 443;
    oHTTP2.TLS := True;

    oGRPC := TsgcGRPCClient.Create(nil);
    oGRPC.Client := oHTTP2;

    // service-account JWT authentication
    oGRPC.GoogleCloudOptions.JWT.KeyFile := 'service-account.json';
    oGRPC.GoogleCloudOptions.JWT.API_Endpoint := 'https://translate.googleapis.com/';
    oGRPC.DefaultMetadata.AddValue('authorization', 'Bearer ' + oGRPC.GoogleCloudOptions.JWT.Token);

    // build the typed request and call the method
    oRequest := TsgcGRPCTranslationTranslateTextRequest.Create;
    try
      oRequest.Parent := 'projects/my-project-id/locations/global';
      oRequest.Contents.Add('Hello, world!');
      oRequest.SourceLanguageCode := 'en';
      oRequest.TargetLanguageCode := 'es';
      oResponse := oGRPC.Call('google.cloud.translation.v3.TranslationService', 'TranslateText', oRequest.ToBytes);
      ShowMessage(oResponse.DataString);
    finally
      oRequest.Free;
    end;

Methods

NameDescription
TranslateTextTranslates one or more text strings from a source language to a target language.
DetectLanguageDetects the language of the supplied text.
GetSupportedLanguagesReturns the list of languages supported for translation.

Demo

A working sample is available in the demo folder Demos/21.GRPC/12.Translation, which shows how to authenticate and translate text with the TranslateText method.

See Also