Using the Natural Language API with C#

In this codelab you will focus on using the Natural Language API with C#. You will learn how to perform sentiment, entity and syntax analysis.

The Google Cloud Natural Language API provides natural language understanding technologies to developers, including sentiment analysis, entity analysis, and syntax analysis.

What you'll learn

  • How to use the Cloud Shell
  • How to Enable the Natural Language API
  • How to Authenticate API requests
  • How to install the Google Cloud client library for C#
  • How to perform Sentiment Analysis
  • How to perform Entity Analysis
  • How to perform Syntax Analysis

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

H_hgylo4zxOllHaAbPKJ7VyqCKPDUnDhkr-BsBIFBsrB6TYSisg6LX-uqmMhh4sXUy_hoa2Qv87C2nFmkg-QAcCiZZp0qtpf6VPaNEEfP_iqt29KVLD-gklBWugQVeOWsFnJmNjHDw

dcCPqfBIwNO4R-0fNQLUC4aYXOOZhKhjUnakFLZJGeziw2ikOxGjGkCHDwN5x5kCbPFB8fiOzZnX-GfuzQ8Ox-UU15BwHirkVPR_0RJwl0oXrhqZmMIvZMa_uwHugBJIdx5-bZ6Z8Q

jgLzVCxk93d6E2bbonzATKA4jFZReoQ-fORxZZLEi5C3D-ubnv6nL-eP-iyh7qAsWyq_nyzzuEoPFD1wFOFZOe4FWhPBJjUDncnTxTImT3Ts9TM54f4nPpsAp52O0y3Cb19IceAEgQ

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.

Activate Cloud Shell

  1. From the Cloud Console, click Activate Cloud Shell dnDTxS9j60RcXdTjea12HLB9paS9Gzf7PfFLE9RW8g0Qx1bz7nmCzyCu4rjluX3bOEwavOpDwioXEkzOf6xtZp6-ZbJa08jwJqtmeeW8jZ1tYfi2lyXqvW3WFHP0eAxDkQDfpO9Ljw.

yzBQBp2RC1EFvSSLYVkMA2m6LHqGsp22O81rUS5tGb9Y1FqlVhoRj_ka8V_uEjtpcirZRULMy1IjNr848uYvb9mC9RcGGqeayaLcXFfRwUGeXWChZPtWkHzUshTcqx_wJHis0X8viA

If you've never started Cloud Shell before, you're presented with an intermediate screen (below the fold) describing what it is. If that's the case, click Continue (and you won't ever see it again). Here's what that one-time screen looks like:

VgsaqGbKPRiqK24CqAKjSXjepuJT96PmiDqQMcySmWKx8QyW5F3G2D8JH2d08ek-YM77wWKxPvggpOFER8Hbq3aaZipTDU2o0il7A0kS3FXY_NzuujjEqDF1nsbDKkNMThrqcdMGtQ

It should only take a few moments to provision and connect to Cloud Shell.

7RuYr-LCKzdiE1veTFmL_lYrVxsMZ6-xDoxAnfwPPc5uFA0utmFGejvu81jGmTdbqnqxrytW3KcHT6xrMIRc3bskctnDZC5nJdpqw-LRxu3r35hL4A0BSBTtbtirfh3PKv-eOKt8Rg

This virtual machine is loaded with all the development tools you need. It offers a persistent 5GB home directory and runs in Google Cloud, greatly enhancing network performance and authentication. Much, if not all, of your work in this codelab can be done with simply a browser or your Chromebook.

Once connected to Cloud Shell, you should see that you are already authenticated and that the project is already set to your project ID.

  1. Run the following command in Cloud Shell to confirm that you are authenticated:
gcloud auth list

Command output

 Credentialed Accounts
ACTIVE  ACCOUNT
*       <my_account>@<my_domain.com>

To set the active account, run:
    $ gcloud config set account `ACCOUNT`
gcloud config list project

Command output

[core]
project = <PROJECT_ID>

If it is not, you can set it with this command:

gcloud config set project <PROJECT_ID>

Command output

Updated property [core/project].

Before you can begin using the Natural Language API you must enable the API. Using the Cloud Shell you can enable the API by using the following command:

gcloud services enable language.googleapis.com

In order to make requests to the Natural Language 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 Natural Language 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)

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

gcloud iam service-accounts create my-nl-sa \
  --display-name "my nl 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-nl-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com

Finally, set the GOOGLE_APPLICATION_CREDENTIALS environment variable, which is used by the Natural Language 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 Natural Language API.

First, create a simple C# console application that you will use to run Natural Language API samples:

dotnet new console -n NaturalLanguageApiDemo

You should see the application created and dependencies resolved:

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

Next, navigate to NaturalLanguageApiDemo folder:

cd NaturalLanguageApiDemo/

And add Google.Cloud.Language.V1 NuGet package to the project:

dotnet add package Google.Cloud.Language.V1
info : Adding PackageReference for package 'Google.Cloud.Language.V1' into project '/home/atameldev/NaturalLanguageApiDemo/NaturalLanguageApiDemo.csproj'.
log  : Restoring packages for /home/atameldev/NaturalLanguageApiDemo/NaturalLanguageApiDemo.csproj...
...
info : PackageReference for package 'Google.Cloud.Language.V1' version '1.1.0' added to file '/home/atameldev/NaturalLanguageApiDemo/NaturalLanguageApiDemo.csproj'.

Now, you're ready to use Natural Language API!

In this section you will perform Sentiment Analysis on a string and find out the Score and Magnitude using the Natural Language API.

The Score of the sentiment ranges between -1.0 (negative) and 1.0 (positive) and corresponds to the overall sentiment from the given information.

The Magnitude of the sentiment ranges from 0.0 to +infinity and indicates the overall strength of sentiment from the given information. The more information that is provided the higher the magnitude.

Open the code editor from the top right side of the Cloud Shell:

9b8f365ab5ec7f71.png

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

using System;
using Google.Cloud.Language.V1;

namespace NaturalLanguageApiDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var text = "Yukihiro Matsumoto is great!";
            var client = LanguageServiceClient.Create();
            var response = client.AnalyzeSentiment(Document.FromPlainText(text));
            var sentiment = response.DocumentSentiment;
            Console.WriteLine($"Score: {sentiment.Score}");
            Console.WriteLine($"Magnitude: {sentiment.Magnitude}");
        }
    }
}

Take a minute or two to study the code and see how the snippet of code is used to perform sentiment analysis on the string "Yukihiro Matsumoto is great!".

Back in Cloud Shell, run the app:

dotnet run

You should see the following output:

Score: 0.9
Magnitude: 0.9

Summary

In this step, you were able to perform Sentiment Analysis on a string of text and print out the score and magnitude. Read more about Sentiment Analysis.

Entity analysis inspects the given information for entities by searching for proper nouns such as public figures, landmarks, etc., and returns information about those entities.

To perform Entity analysis, navigate to the Program.cs file inside the NaturalLanguageApiDemo folder and replace the code with the following:

using System;
using Google.Cloud.Language.V1;

namespace NaturalLanguageApiDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var text = "Yukihiro Matsumoto is great!";
            var client = LanguageServiceClient.Create();
            var response = client.AnalyzeEntitySentiment(Document.FromPlainText(text));

            foreach (var entity in response.Entities)
            {
                Console.WriteLine($"Entity: \"{entity.Name}\" ({entity.Type})");
                if (entity.Metadata.ContainsKey("wikipedia_url"))
                {
                    Console.WriteLine($"URL: {entity.Metadata["wikipedia_url"]}");
                }
            }
        }
    }
}

Take a minute or two to study the code and see how the snippet of code is used to perform entity analysis on the string "Yukihiro Matsumoto is great!".

Back in Cloud Shell, run the app:

dotnet run

You should see the following output:

Entity: "Yukihiro Matsumoto" (Person)
URL: https://en.wikipedia.org/wiki/Yukihiro_Matsumoto

Summary

In this step, you were able to perform Entity Analysis on a string of text and printed its entities. Read more about Entity Analysis.

Syntactic Analysis extracts linguistic information, breaking up the given text into a series of sentences and tokens (generally, word boundaries), providing further analysis on those tokens.

This example will print out the number of sentences, tokens, and provide the part of speech for each token.

To perform Syntax Analysis, navigate to the Program.cs file inside the NaturalLanguageApiDemo folder and replace the code with the following:

using System;
using Google.Cloud.Language.V1;
using static Google.Cloud.Language.V1.AnnotateTextRequest.Types;

namespace NaturalLanguageApiDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var text = "Yukihiro Matsumoto is great!";
            var client = LanguageServiceClient.Create();
            var response = client.AnnotateText(Document.FromPlainText(text), 
                new Features { ExtractSyntax = true });

            var sentences = response.Sentences;
            var tokens = response.Tokens;

            Console.WriteLine($"Sentences: {sentences.Count}");
            Console.WriteLine($"Tokens: {tokens.Count}");

            foreach (var token in tokens)
            {
                Console.WriteLine($"{token.PartOfSpeech.Tag} {token.Text.Content}");
            }
        }
    }
}

Take a minute or two to study the code and see how the snippet of code is used to perform syntax analysis on the string "Yukihiro Matsumoto is great!".

Back in Cloud Shell, run the app:

dotnet run

You should see the following output:

Sentences: 1
Tokens: 5
Noun Yukihiro
Noun Matsumoto
Verb is
Adj great
Punct !

A visual interpretation is shown below.

568ec7ea91511a42.png

Summary

In this step, you were able to perform Syntax Analysis on a simple string of text and printed out the number of sentences, number of tokens, and linguistic information for each token. Read more about Syntax Analysis.

You learned how to use the Natural Language API using C# to perform different kinds of analyses on information!

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.