Analyze Sentiment with Natural Language API
Checkpoints
Get an API Key
/ 50
Set up your Google Doc
/ 50
Using the Natural Language API from Google Docs
GSP126
Overview
The Natural Language API is a pretrained machine learning model that can analyze syntax, extract entities, and evaluate the sentiment of text. You can call the Natural Language API from Google Docs to perform all of these functions.
This lab focuses on calling the Natural Language API from Google Docs. You use the Natural Language API to recognize the sentiment of selected text in a Google Doc and highlight it based on that sentiment.
When you complete this lab, you are able to select text in a document and mark its sentiment, using a menu choice, as shown below.
Text is highlighted in red for negative sentiment, green for positive sentiment, and yellow for neutral sentiment.
What you'll learn
In this lab, you learn how to:
- Call the Natural Language API from Google Docs
- Add menus to Google Docs
- Recognize and work with selected text in Google Docs
Setup and requirements
Before you click the Start Lab button
Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.
This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.
To complete this lab, you need:
- Access to a standard internet browser (Chrome browser recommended).
- Time to complete the lab---remember, once you start, you cannot pause a lab.
How to start your lab and sign in to the Google Cloud console
-
Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:
- The Open Google Cloud console button
- Time remaining
- The temporary credentials that you must use for this lab
- Other information, if needed, to step through this lab
-
Click Open Google Cloud console (or right-click and select Open Link in Incognito Window if you are running the Chrome browser).
The lab spins up resources, and then opens another tab that shows the Sign in page.
Tip: Arrange the tabs in separate windows, side-by-side.
Note: If you see the Choose an account dialog, click Use Another Account. -
If necessary, copy the Username below and paste it into the Sign in dialog.
{{{user_0.username | "Username"}}} You can also find the Username in the Lab Details panel.
-
Click Next.
-
Copy the Password below and paste it into the Welcome dialog.
{{{user_0.password | "Password"}}} You can also find the Password in the Lab Details panel.
-
Click Next.
Important: You must use the credentials the lab provides you. Do not use your Google Cloud account credentials. Note: Using your own Google Cloud account for this lab may incur extra charges. -
Click through the subsequent pages:
- Accept the terms and conditions.
- Do not add recovery options or two-factor authentication (because this is a temporary account).
- Do not sign up for free trials.
After a few moments, the Google Cloud console opens in this tab.
Task 1. Enable the Natural Language API
Before you start, make sure that the Natural Language API is enabled.
-
In the Google Cloud console, select Navigation menu > APIs & Services > Library.
-
Search for Cloud Natural Language API and click on the API to enable it or to confirm that the API is enabled.
Task 2. Get an API key
Generate an API user key to pass in the request URL.
-
To create an API key, select Navigation menu > APIs & Services > Credentials.
-
Click Create credentials at the top and select API key:
-
Copy the API key to a text file or a Google Doc to use in a later step. Click Close.
Once you have the API key, you are ready to move into Google Docs.
Click Check my progress to verify the objective.
Task 3. Set up your Google Doc
Before you call the Natural Language API, make an Apps Script program to create the menu, link it to a function to mark the text, and extract the text from the user selection.
- Create a new Google Doc.
- From within your new document, select the menu item Extensions > Apps Script.
- Delete any code in the script editor and paste in the code below. This code creates a menu item, extracts the text from the current selected text, and highlights the text based on its sentiment. It does not call the Natural Language API yet.
- On the menu bar, click Save project (
). (The script's name is shown to end users in several places, including the authorization dialog.)
- Return to your document. Add text to your document. You can use the sample that comes from Alice in Wonderland on Project Gutenberg (copy and paste the
Plain Text UTF-8
version into the document), but feel free to use any text you wish. - Reload the document to see the new menu, Natural Language Tools, which you created, appear in the Google Docs toolbar.
- Select text and then the Mark Sentiment option from the Natural Language Tools menu. The first time you select this option, you are prompted to authorize the script to run. Click Continue, and then confirm your account.
- Allow Natural Language Tools to view and manage documents that this application has been installed in.
- Once the script is authorized, the selected text is highlighted in yellow, since the stub for sentiment analysis always returns 0.0, which is neutral.
Click Check my progress to verify the objective.
Task 4. Call the Natural Language API
Once your program can extract text from the selection and highlight it, it's time to call the Natural Language API. All of this is done in the body of the retrieveSentiment
function.
- Return to the Extensions > Apps Script in Google Docs.
- In the
retrieveSentiment
function, replace "your key here" with your actual API key from the Google Cloud Console.
- Create a variable to hold the URL of the Natural Language API with your API key appended to it (do not modify this line):
- Build a structure from the line passed into the function that holds the text of the line, along with its type and language. Currently the only supported language is English.
- Build the entire data payload from the document details by adding the encoding type:
- Create a structure containing the payload and the necessary header information:
- Make the call, saving the response:
- The response is returned in JSON format; parse it and extract the score field, if it exists. Return either that field or 0.0.
The complete code to retrieve the sentiment is below:
- Save your script, reload the document, and try out the full program. You may need to re-authorize with your credentials to enable the new functionality. Select different sections of your document to see how the sentiment may differ over its parts.
- (Optional) Type and then analyze your own words. For example, type and analyze "I'm mad", and then type and analyze "I'm happy". Experiment to see how the Natural Language API interprets different groups, for example if you analyze "I'm happy. I'm happy. I'm sad.". What happens if you add another "I'm sad."?
Congratulations!
Congratulations! You created a Google Doc and called the Natural Language API to analyze the sentiment of selected portions of the document.
Next steps / Learn more
Continue your Google Cloud learning with these suggestions:
- Take more labs. Learn more about the Natural Language API by taking labs, like Entity and Sentiment analysis with the Natural Language API. Or take something completely different like Rent-a-VM to Process Earthquake Data.
- Start a quest. A quest is a series of related labs that form a learning path. Completing a quest earns you a digital badge, to recognize your achievement. You can make your badge (or badges) public and link to them in your online resume or social media account. Refer to the Google Cloud Skills Boost catalog for all available quests.
Google Cloud training and certification
...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.
Manual Last Updated July 17, 2024
Lab Last Tested July 17, 2024
Copyright 2024 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.