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

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

What you'll need

Survey

How will you use this tutorial?

Read it through only Read it and complete the exercises

How would you rate your experience with Ruby?

Novice Intermediate Proficient

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

Novice Intermediate Proficient

Self-paced environment setup

If you don't already have a Google Account (Gmail or Google Apps), you must create one. Sign-in to Google Cloud Platform console (console.cloud.google.com) and create a new project:

Screenshot from 2016-02-10 12:45:26.png

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.

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

Running through this codelab shouldn't cost you more than a few dollars, but it could be more if you decide to use more resources or if you leave them running (see "cleanup" section at the end of this document).

New users of Google Cloud Platform are eligible for a $300 free trial.

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 Google Cloud Shell

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

Then click "Start Cloud Shell":

It should only take a few moments to provision and connect to the environment:

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

Once connected to the cloud shell, you should see that you are already authenticated and that the project is already set to your PROJECT_ID.

Run the following command in the cloud shell to confirm that you are authenticated:

gcloud auth list

Command output

Credentialed accounts:
 - <myaccount>@<mydomain>.com (active)
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 is an account, belonging to your project, that is used by the Google Client Ruby 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="<PROJECT_ID>"

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 Ruby 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 Ruby gem, 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.

Install the Google Cloud Natural Language Ruby gem using the following command:

gem install google-cloud-language

You can read more about the set of Google Cloud service Ruby gems available for different APIs here.

Now that you have installed the required gem, start an Interactive Ruby session using the irb command:

irb --noecho

IRB will run the Ruby interpreter in a Read, Eval, Print, Loop session and --noecho will disable printing the result of each command entered during the session.

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.

To perform sentiment analysis, copy the following Ruby code and paste it into your IRB session:

require "google/cloud/language"

language = Google::Cloud::Language.new

text_content = "Yukihiro Matsumoto is great!"
response     = language.analyze_sentiment content: text_content, 
                                          type: :PLAIN_TEXT
sentiment = response.document_sentiment

puts "Score: #{sentiment.score}"
puts "Magnitude: #{sentiment.magnitude}"

This snippet of code will perform sentiment analysis on the string "Yukihiro Matsumoto is great!". The score and magnitude will be printed similar to:

Score: 0.8999999761581421
Magnitude: 0.8999999761581421

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, copy the following Ruby code and paste it into your IRB session.

require "google/cloud/language"

language = Google::Cloud::Language.new

text_content = "Yukihiro Matsumoto is great!"
response     = language.analyze_entities content: text_content,
                                         type: :PLAIN_TEXT

entities = response.entities

entities.each do |entity|
  puts "Entity: #{entity.name} #{entity.type}"
  
  if entity.metadata["wikipedia_url"]
    puts "URL: #{entity.metadata['wikipedia_url']}"
  end
end

In this example you performed entity analysis on the string "Yukihiro Matsumoto is great!". You should have seen 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, copy the following Ruby code and paste it into your IRB session.

require "google/cloud/language"

language = Google::Cloud::Language.new

text_content = "Yukihiro Matsumoto is great!"
response     = language.analyze_syntax content: text_content,
                                       type: :PLAIN_TEXT

sentences = response.sentences
tokens    = response.tokens

puts "Sentences: #{sentences.count}"
puts "Tokens: #{tokens.count}"

tokens.each do |token|
  puts "#{token.part_of_speech.tag} #{token.text.content}"
end

In this example you performed syntax analysis on the string "Yukihiro Matsumoto is great!". You should have seen the following output:

A visual interpretation is shown below.

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 Ruby 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:

Learn More

License

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