Using the Translation API with C#

    1. Overview

    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, suchChrome orFirefox
    • Familiarity using C#

    Survey

    How will you use this tutorial?

    Read it through onlyRead it and complete the exercises

    How would you rate your experience with C#?

    NoviceIntermediateProficient

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

    NoviceIntermediateProficient

    2. Setup and Requirements

    Self-paced environment setup

    1. Sign-in to theGoogle Cloud Console and create a new project or reuse an existing one. If you don't already have a Gmail or Google Workspace account, you mustcreate one.

    295004821bab6a87.png

    37d264871000675d.png

    96d86d3d5655cdbe.png

    • TheProject name is the display name for this project's participants. It is a character string not used by Google APIs. You can always update it.
    • TheProject ID is unique across all Google Cloud projects and is immutable (cannot be changed after it has been set). The Cloud Console auto-generates a unique string; usually you don't care what it is. In most codelabs, you'll need to reference your Project ID (typically identified asPROJECT_ID). If you don't like the generated ID, you might generate another random one. Alternatively, you can try your own, and see if it's available. It can't be changed after this step and remains for the duration of the project.
    • For your information, there is a third value, aProject Number, which some APIs use. Learn more about all three of these values in thedocumentation.

    Caution: A project ID is globally unique and can't be used by anyone else after you've selected it. You are the only user of that ID. Even if a project is deleted, the ID can't be used again

    Note: If you use a Gmail account, you can leave the default location set toNo organization. If you use a Google Workspace account, choose a location that makes sense for your organization.

    1. Next, you'll need toenable billing in the Cloud Console to use Cloud resources/APIs. Running through this codelab won't cost much, if anything at all. To shut down resources to avoid incurring billing beyond this tutorial, you can delete the resources you created or delete the project. New Google Cloud users are eligible for the$300 USD Free Trial program.

    Start Cloud Shell

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

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

    84688aa223b1c3a2.png

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

    320e18fedb7fbe0.png

    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 codelab can be done within a browser. You do not need to install anything.

    3. Enable the Translation API

    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:

    gcloudservicesenabletranslate.googleapis.com

    Note: If this command ERRORs, check that the current Project ID matches your codelab Project ID.

    Use the following command to find the current Project ID being used by Cloud Shell:

    gcloud info | grep "project"

    If the Project ID is not correct, use the following command to use the correct Project ID:

    gcloud config set project <PROJECT_ID>

    Replace<PROJECT_ID> with the correct Project ID.

    4. Install the Google Cloud Translation API client library for C#

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

    dotnetnewconsole-nTranslationApiDemoThetemplate"Console Application"wascreatedsuccessfully.Processingpost-creationactions......Restoresucceeded.

    Next, navigate toTranslationApiDemo folder and addGoogle.Cloud.Translation.V2 NuGet package to the project:

    cdTranslationApiDemo/dotnetaddpackageGoogle.Cloud.Translation.V2info:AddingPackageReferenceforpackage'Google.Cloud.Translation.V2'intoproject'/home/atameldev/TranslationDemo/TranslationDemo.csproj'.log:Restoringpackagesfor/home/atameldev/TranslationDemo/TranslationDemo.csproj......info:PackageReferenceforpackage'Google.Cloud.Translation.V2'version'1.0.0'addedtofile'/home/atameldev/TranslationDemo/TranslationDemo.csproj'.

    Now, you're ready to use the Translation API!

    5. List Available Languages

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

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

    fd3fc1303e63572.png

    Navigate to theProgram.cs file inside theTranslationApiDemo folder and replace the code with the following:

    usingSystem;usingGoogle.Cloud.Translation.V2;namespaceTranslationApiDemo{classProgram{staticvoidMain(string[]args){varclient=TranslationClient.Create();foreach(varlanguageinclient.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:

    dotnetrunafAfrikaanssqAlbanianamAmharicarArabichyArmenianazAzerbaijanieuBasquebeBelarusian...yiYiddishyoYorubazuZulu

    Note: If this C# code does not work for you, verify the instructions you performed duringAuthenticate API requests step.

    Using the following command to verify the value ofGOOGLE_APPLICATION_CREDENTIALS environment variable:

    echo GOOGLE_APPLICATION_CREDENTIALS

    It should output the value"~/key.json".

    If it does, next check that a service account was created and is located at"~/key.json" by using:

    cat "~/key.json"

    You should see something similar to:

    {

    "type": "service_account",

    "project_id": "PROJECT_ID",

    "private_key_id": "ff31939192529e07f42e4535fb20bb029def1276",

    "Private_key":...

    If you don't, revisit theAuthenticate API requests step.

    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 theLanguage Support page.

    6. Translate text

    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 theProgram.cs file inside theTranslationApiDemo folder and replace the code with the following:

    usingSystem;usingGoogle.Cloud.Translation.V2;namespaceTranslationApiDemo{classProgram{staticvoidMain(string[]args){varclient=TranslationClient.Create();vartext="Hello World!";varresponse=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:

    dotnetrunSelamDünya!

    Summary

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

    7. Detect language

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

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

    usingSystem;usingGoogle.Cloud.Translation.V2;namespaceTranslationApiDemo{classProgram{staticvoidMain(string[]args){varclient=TranslationClient.Create();vartext="Selam Dünya!";vardetection=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:

    dotnetrunLanguage:trConfidence:1

    Summary

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

    8. Congratulations!

    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 theCloud 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.

    Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.