Using the Translation API with C#

Google Cloud Translation API provides a simple programmatic interface for dynamically translating an arbitrary string into any supported language using state-of-the-art Neural Machine Translation. It can also be used to detect language in cases where the source language is unknown.

In this codelab, you will focus on using the Translation API with C#. You will learn how to list available languages, translate text and also detect language of a given text.

What you'll learn

  • How to use the Cloud Shell
  • How to enable the Translation API
  • How to Authenticate API requests
  • How to install the Google Cloud client library for C#
  • How to list available languages
  • How to translate text
  • How to detect language

What you'll need

  • A Google Cloud Platform Project
  • A Browser, such Chrome or Firefox
  • Familiarity using C#

Survey

How will you use this tutorial?

Read it through only Read it and complete the exercises

How would you rate your experience with C#?

Novice Intermediate Proficient

How would you rate your experience with using Google Cloud Platform services?

Novice Intermediate Proficient

Self-paced environment setup

  1. Sign in to Cloud Console and create a new project or reuse an existing one. (If you don't already have a Gmail or G Suite account, you must create one.)

dMbN6g9RawQj_VXCSYpdYncY-DbaRzr2GbnwoV7jFf1u3avxJtmGPmKpMYgiaMH-qu80a_NJ9p2IIXFppYk8x3wyymZXavjglNLJJhuXieCem56H30hwXtd8PvXGpXJO9gEUDu3cZw

ci9Oe6PgnbNuSYlMyvbXF1JdQyiHoEgnhl4PlV_MFagm2ppzhueRkqX4eLjJllZco_2zCp0V0bpTupUSKji9KkQyWqj11pqit1K1faS1V6aFxLGQdkuzGp4rsQTan7F01iePL5DtqQ

8-tA_Lheyo8SscAVKrGii2coplQp2_D1Iosb2ViABY0UUO1A8cimXUu6Wf1R9zJIRExL5OB2j946aIiFtyKTzxDcNnuznmR45vZ2HMoK3o67jxuoUJCAnqvEX6NgPGFjCVNgASc-lg

Remember the project ID, a unique name across all Google Cloud projects (the name above has already been taken and will not work for you, sorry!). It will be referred to later in this codelab as PROJECT_ID.

  1. Next, you'll need to enable billing in Cloud Console in order to use Google Cloud resources.

Running through this codelab shouldn't cost much, if anything at all. Be sure to to follow any instructions in the "Cleaning up" section which advises you how to shut down resources so you don't incur billing beyond this tutorial. New users of Google Cloud are eligible for the $300USD Free Trial program.

Start Cloud Shell

While Google Cloud can be operated remotely from your laptop, in this codelab you will be using Google Cloud Shell, a command line environment running in the Cloud.

From the GCP Console click the Cloud Shell icon on the top right toolbar:

E0b6xMEnCN6XCtm5OITZ-CHPnhUsO3WrGGJFu0Yr587eWRPZG2xj4U9wHbTxF8d1LTHnk5yzgMxEbhAmTCwbNH8rMoQV70pEkLkz54gtUHD7kRtiSI_2EqrighTDFbuoO0Z146CC3Q

It should only take a few moments to provision and connect to the environment. When it is finished, you should see something like this:

kXnInzErAjsyeUStcIiTdNi179GwXpgp-2YTay2z0DW_7PoZ7uPWiKlaYk0LXNwv2kvkqUZEjhWjAgwNsgkX4Kpkhu8duXo5FTsog9bM405TSmdC_BUIX4ywkMV-tEc1VHtUzdTykg

This virtual machine is loaded with all the development tools you'll need. It offers a persistent 5GB home directory, and runs on Google Cloud, greatly enhancing network performance and authentication. All of your work in this lab can be done with simply a browser.

Before you can begin using the Translation API, you must enable the API. You can enable the API by using the following command in the Cloud Shell:

gcloud services enable translate.googleapis.com

In order to make requests to the Translation API, you need to use a Service Account. A Service Account belongs to your project and it is used by the Google Client C# library to make Translation API requests. Like any other user account, a service account is represented by an email address. In this section, you will use the Cloud SDK to create a service account and then create credentials you will need to authenticate as the service account.

First, set an environment variable with your PROJECT_ID which you will use throughout this codelab:

export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value core/project)

Test that it was set correctly:

echo ${GOOGLE_CLOUD_PROJECT}

yourproject-XXXX

Next, create a new service account to access the Translation API by using:

gcloud iam service-accounts create my-translation-sa \
  --display-name "my translation codelab service account"

Next, create credentials that your C# code will use to login as your new service account. Create these credentials and save it as a JSON file "~/key.json" by using the following command:

gcloud iam service-accounts keys create ~/key.json \
  --iam-account  my-translation-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com

Finally, set the GOOGLE_APPLICATION_CREDENTIALS environment variable, which is used by the Translation API C# library, covered in the next step, to find your credentials. The environment variable should be set to the full path of the credentials JSON file you created, by using:

export GOOGLE_APPLICATION_CREDENTIALS="/home/${USER}/key.json"

You can read more about authenticating the Translation API.

First, create a simple C# console application that you will use to run Translation API samples.

dotnet new console -n TranslationApiDemo

The template "Console Application" was created successfully.
Processing post-creation actions...
...
Restore succeeded.

Next, navigate to TranslationApiDemo folder and add Google.Cloud.Translation.V2 NuGet package to the project:

cd TranslationApiDemo/
dotnet add package Google.Cloud.Translation.V2

info : Adding PackageReference for package 'Google.Cloud.Translation.V2' into project '/home/atameldev/TranslationDemo/TranslationDemo.csproj'.
log  : Restoring packages for /home/atameldev/TranslationDemo/TranslationDemo.csproj...
...
info : PackageReference for package 'Google.Cloud.Translation.V2' version '1.0.0' added to file '/home/atameldev/TranslationDemo/TranslationDemo.csproj'.

Now, you're ready to use Translation API!

In this section, you will first list all available languages in Translation API.

First, open the code editor from the top right side of the Cloud Shell:

9b8f365ab5ec7f71.png

Navigate to the Program.cs file inside the TranslationApiDemo folder and replace the code with the following:

using System;
using Google.Cloud.Translation.V2;

namespace TranslationApiDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = TranslationClient.Create();
            foreach (var language in client.ListLanguages(LanguageCodes.English))
            {
                Console.WriteLine($"{language.Code}\t{language.Name}");
            }
        }
    }
}

Take a minute or two to study the code*.* Note that we are listing the language names in English but it can be listed in any language.

Back in Cloud Shell, run the app. You should see the following output:

dotnet run

af        Afrikaans
sq        Albanian
am        Amharic
ar        Arabic
hy        Armenian
az        Azerbaijani
eu        Basque
be        Belarusian
...
yi        Yiddish
yo        Yoruba
zu        Zulu

Summary

In this step, you were able to list all available languages in Translation API. You can find the complete list of supported languages on the Language Support page.

You can use Translate API to translate a text in one language into another language. Text is translated using the Neural Machine Translation (NMT) model. If the NMT model is not supported for the requested language translation pair, then the Phrase-Based Machine Translation (PBMT) model is used.

To translate text, navigate to the Program.cs file inside the TranslationApiDemo folder and replace the code with the following:

using System;
using Google.Cloud.Translation.V2;

namespace TranslationApiDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = TranslationClient.Create();
            var text = "Hello World!";
            var response = client.TranslateText(text, LanguageCodes.Turkish, LanguageCodes.English);
            Console.WriteLine(response.TranslatedText);
        }
    }
}

Take a minute or two to study the code. It translates the text "Hello World" from English to Turkish*.*

Back in Cloud Shell, run the app. You should see the following output:

dotnet run

Selam Dünya!

Summary

In this step, you were able to use Translation API to translate a text from English to Turkish. Read more about Translating text.

You can use Translate API to also detect the language of a text string.

To detect language, navigate to the Program.cs file inside the TranslationApiDemo folder and replace the code with the following:

using System;
using Google.Cloud.Translation.V2;

namespace TranslationApiDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = TranslationClient.Create();
            var text = "Selam Dünya!";
            var detection = client.DetectLanguage(text);
            Console.WriteLine($"Language: {detection.Language}\tConfidence: {detection.Confidence}");
        }
    }
}

Take a minute or two to study the code. It detects the language of the text "Selam Dünya!" which happens to be a Turkish phrase*.*

Back in Cloud Shell, run the app. You should see the following output:

dotnet run

Language: tr        Confidence: 1

Summary

In this step, you were able to detect the language of a piece of text using Translation API. Read more about Detecting language.

You learned how to use the Translation API using C#!

Clean up

To avoid incurring charges to your Google Cloud Platform account for the resources used in this quickstart:

  • Go to the Cloud Platform Console.
  • Select the project you want to shut down, then click ‘Delete' at the top: this schedules the project for deletion.

Learn More

License

This work is licensed under a Creative Commons Attribution 2.0 Generic License.