The Natural Language API lets you extract entities, sentiment, and syntax from your text.Real world example is customer feedback platform. In this tutorial, I’ll introduce you to the Cloud Natural Language platform and show you how to use it to analyze text.

Prerequisites


  • Google Cloud Platform account(You can use 12 months free trial)

1.Acquiring an API Key


To Use Google Cloud Natural Language API services in the app, you need an API key. You can get one by creating a new project in the Google Cloud Platform console. Once the project has been created, go to API Manager > Dashboard and press the Enable API button. Enable Natural Language API To get API key, go to the Credentials tab, press the Create Credentials button, and select API key. Google Cloud Vision API Key

2.Creating a New Android Project


Google provides client libraries to simplify the process of building and sending requests and receiving and parsing responses. Add the following compile dependencies to the app build.gradle:

android {
    ....
    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
    }
}
dependencies {
    ....
   compile group: 'com.google.apis', name: 'google-api-services-language', version: 'v1-rev388-1.22.0' exclude module: 'httpclient'
   compile group: 'com.google.api-client', name: 'google-api-client-android', version: '1.22.0' exclude module: 'httpclient'
}

Add INTERNET permission in the AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET"/>

To interact with the API using the Google API Client library, you must create a CloudNaturalLanguage object using the CloudNaturalLanguage.Builder class. Its constructor also expects an HTTP transport and a JSON factory. Furthermore, by assigning a CloudNaturalLanguageRequestInitializer instance to it, you can force it to include your API key in all its requests.

naturalLanguageService = new CloudNaturalLanguage.Builder(
                AndroidHttp.newCompatibleTransport(),
                new AndroidJsonFactory(),
                null
        ).setCloudNaturalLanguageRequestInitializer(
                new CloudNaturalLanguageRequestInitializer(API_KEY)
        ).build();

All the text you want to analyze using the API must be placed inside a Document object. The Document object must also contain configuration information, such as the language of the text and whether it is formatted as plain text or HTML. Add the following code:

Document document = new Document();
document.setType("PLAIN_TEXT");
document.setLanguage("en-US");
document.setContent(transcript);

Next, you must create a Features object specifying the features you are interested in analyzing. The following code shows you how to create a Features object that says you want to extract entities and run sentiment analysis only.

Features features = new Features();
features.setExtractEntities(true);
features.setExtractDocumentSentiment(true);

Use the Document and Features objects to compose an AnnotateTextRequest object, which can be passed to the annotateText() method to generate an AnnotateTextResponse object.

new AsyncTask<Object, Void, AnnotateTextResponse>() {
         @Override
         protected AnnotateTextResponse doInBackground(Object... params) {
                AnnotateTextResponse response = null;
                try {
                     response = naturalLanguageService.documents().annotateText(request).execute();
                } catch (IOException e) {
                     e.printStackTrace();
                }
                return response;
         }
         @Override
         protected void onPostExecute(AnnotateTextResponse response) {
              super.onPostExecute(response);
              if (response != null) {
                    Sentiment sent = response.getDocumentSentiment();
                    entityList.addAll(response.getEntities());
                    entityListAdapter.notifyDataSetChanged();
                    sentiment.setText("Score : " + sent.getScore() + " Magnitude : " + sent.getMagnitude());
              }
         }
}.execute();

Entity Analysis


We get the name of the entity, for example, Google.The type of the entity is organisation. Then we get back some metadata.MID ID that maps to Google’s Knowledge Graph. You can extract a list of entities from the AnnotateTextResponse object by calling its getEntities() method. Analyze Entity

Sentiment Analysis


Analyze the sentiment of your text.If we have this restaurant review,

The food at that restaurant has stale,I will not be going back.

If I might want to flag the most positive and most negative once and then respond just to those. So we get two number back from the Natural Language API to help us do this. The first thing we get back is score, which will tell us on a scale from -1 to 1 how positive or negative is this text? In this example, we get negative 0.8, which is almost fully negative. Then we get magnitude, which tells us regardless of being positive or negative, how strong is the sentiment in this text?And this is a range from 0 to infinity, and it’s normalize based on the length of the text.So we get a pretty small number here,0.8 because this is just a small piece of text. You can extract the overall sentiment of the transcript by calling the getDocumentSentiment() method. To get the actual score of the sentiment, however, you must also call the getScore() method, which returns a float. analyze sentiment   Download this project from GitHub

Related Post

Google Cloud Vision API in Android APP Google Cloud Speech API in Android APP]]>