Skip to content

Commit 150a93f

Browse files
jerjoujmdobry
authored andcommitted
Add Cloud Natural Language API sample. (GoogleCloudPlatform#155)
* Add Cloud Natural Language API sample. This sample makes a request to analyze the entities in text. Change-Id: I387cff7ac70c6f3c00a5b213527b4bd71c6c44dc * Update package.json * Do it right this time
1 parent dc54846 commit 150a93f

File tree

5 files changed

+332
-1
lines changed

5 files changed

+332
-1
lines changed

language/README.md

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# Cloud Natural Language API Sample
2+
3+
These samples demonstrate the use of the
4+
[Google Cloud Natural Language API](https://cloud.google.com/natural-language/docs/).
5+
6+
`analyze.js` is a command-line program that demonstrates how different methods
7+
of the API can be called.
8+
9+
## Setup
10+
11+
Please follow the [Set Up Your Project](https://cloud-dot-devsite.googleplex.com/natural-language/docs/getting-started#set_up_your_project)
12+
steps in the Quickstart doc to create a project and enable the
13+
Cloud Natural Language API. Following those steps, make sure that you
14+
[Set Up a Service Account](https://cloud.google.com/natural-language/docs/common/auth#set_up_a_service_account),
15+
and export the following environment variable:
16+
17+
```
18+
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your-project-credentials.json
19+
```
20+
21+
## Run locally
22+
23+
First install the needed dependencies.
24+
25+
```
26+
npm install
27+
```
28+
29+
To run:
30+
31+
```
32+
node analyze.js <sentiment|entities|syntax> <text>
33+
```
34+
35+
For example, the following command returns all entities found in the text:
36+
37+
```
38+
node analyze.js entities "President Obama is speaking at the White House."
39+
```
40+
41+
```
42+
{
43+
"entities": [
44+
{
45+
"name": "Obama",
46+
"type": "PERSON",
47+
"metadata": {
48+
"wikipedia_url": "http://en.wikipedia.org/wiki/Barack_Obama"
49+
},
50+
"salience": 0.84503114,
51+
"mentions": [
52+
{
53+
"text": {
54+
"content": "Obama",
55+
"beginOffset": 10
56+
}
57+
}
58+
]
59+
},
60+
{
61+
"name": "White House",
62+
"type": "LOCATION",
63+
"metadata": {
64+
"wikipedia_url": "http://en.wikipedia.org/wiki/White_House"
65+
},
66+
"salience": 0.15496887,
67+
"mentions": [
68+
{
69+
"text": {
70+
"content": "White House",
71+
"beginOffset": 35
72+
}
73+
}
74+
]
75+
}
76+
],
77+
"language": "en"
78+
}
79+
```

language/analyze.js

Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
// Copyright 2016, Google, Inc.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
/**
16+
* @fileoverview Command-line program to demonstrate how to call different
17+
* methods in Cloud Natural Language API.
18+
*
19+
* To run this example, install npm:
20+
* npm install
21+
*
22+
* You must also set up to authenticate with the Cloud APIs using your
23+
* project's service account credentials. See the README for details.
24+
*
25+
* To run:
26+
* node analyze.js <sentiment|entities|syntax> <text>
27+
*
28+
* Here is an example:
29+
* node analyze.js entities "President Obama is speaking at the White House."
30+
*/
31+
'use strict';
32+
33+
var google = require('googleapis');
34+
35+
var languageScopes = ['https://www.googleapis.com/auth/cloud-platform'];
36+
37+
/**
38+
* Gets a client that is connected to the Google Cloud Natural Language API.
39+
*/
40+
function getLanguageService (callback) {
41+
google.auth.getApplicationDefault(function (err, authClient) {
42+
if (err) {
43+
return callback(err);
44+
}
45+
46+
// Depending on the environment that provides the default credentials
47+
// (e.g. Compute Engine, App Engine), the credentials retrieved may
48+
// require you to specify the scopes you need explicitly.
49+
if (authClient.createScopedRequired && authClient.createScopedRequired()) {
50+
authClient = authClient.createScoped(languageScopes);
51+
}
52+
53+
// Load the discovery document for the natural language api service, using
54+
// the acquired credentials.
55+
console.log('Loading language service...');
56+
google.discoverAPI({
57+
url: 'https://language.googleapis.com/$discovery/rest',
58+
version: 'v1beta1',
59+
auth: authClient
60+
}, function (err, languageService) {
61+
if (err) {
62+
return callback(err);
63+
}
64+
callback(null, languageService, authClient);
65+
});
66+
});
67+
}
68+
69+
function analyzeSentiment (inputText, languageService, authClient, callback) {
70+
languageService.documents.analyzeSentiment(
71+
{
72+
auth: authClient,
73+
resource: { // Resource is used as the body for the API call.
74+
document: {
75+
content: inputText,
76+
type: 'PLAIN_TEXT'
77+
}
78+
}
79+
},
80+
function (err, result) {
81+
if (err) {
82+
return callback(err);
83+
}
84+
callback(null, result);
85+
});
86+
}
87+
88+
function analyzeEntities (inputText, languageService, authClient, callback) {
89+
languageService.documents.analyzeEntities(
90+
{
91+
auth: authClient,
92+
resource: { // Resource is used as the body for the API call.
93+
document: {
94+
content: inputText,
95+
type: 'PLAIN_TEXT'
96+
},
97+
encoding_type: 'UTF16'
98+
}
99+
},
100+
function (err, result) {
101+
if (err) {
102+
return callback(err);
103+
}
104+
callback(null, result);
105+
});
106+
}
107+
108+
function analyzeSyntax (inputText, languageService, authClient, callback) {
109+
languageService.documents.annotateText(
110+
{
111+
auth: authClient,
112+
resource: { // Resource is used as the body for the API call.
113+
document: {
114+
content: inputText,
115+
type: 'PLAIN_TEXT'
116+
},
117+
features: {
118+
extract_syntax: 'TRUE'
119+
},
120+
encoding_type: 'UTF16'
121+
}
122+
},
123+
function (err, result) {
124+
if (err) {
125+
return callback(err);
126+
}
127+
callback(null, result);
128+
});
129+
}
130+
131+
// Run the examples.
132+
exports.main = function (command, inputText, callback) {
133+
getLanguageService(function (err, languageService, authClient) {
134+
if (err) {
135+
return callback(err);
136+
}
137+
138+
var resultCallback = function (err, result) {
139+
if (err) {
140+
return callback(err);
141+
}
142+
callback(null, result);
143+
};
144+
if (command === 'sentiment') {
145+
analyzeSentiment(inputText, languageService, authClient, resultCallback);
146+
} else if (command === 'entities') {
147+
analyzeEntities(inputText, languageService, authClient, resultCallback);
148+
} else if (command === 'syntax') {
149+
analyzeSyntax(inputText, languageService, authClient, resultCallback);
150+
} else {
151+
return callback(err);
152+
}
153+
});
154+
};
155+
156+
if (require.main === module) {
157+
var args = process.argv.slice(2);
158+
if (args.length !== 2) {
159+
console.log('Incorrect number of arguments. ' +
160+
'Usage: node analyze.js <sentiment|entities|syntax> <text>');
161+
process.exit(1);
162+
}
163+
if (['sentiment', 'entities', 'syntax'].indexOf(args[0]) === -1) {
164+
console.log('Incorrect command. ' +
165+
'Usage: node analyze.js <sentiment|entities|syntax> <text>');
166+
process.exit(1);
167+
}
168+
exports.main(args[0], args[1], function (result) {
169+
console.log(JSON.stringify(result, null, ' '));
170+
});
171+
}

language/package.json

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
"name": "cloud-natural-language-api-samples",
3+
"version": "1.0.0",
4+
"description": "Samples for using the Google Cloud Natural Language API.",
5+
"repository": {
6+
"type": "git",
7+
"url": "git://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
8+
},
9+
"main": "analyze.js",
10+
"scripts": {
11+
"test": "echo \"Error: no test specified\" && exit 1"
12+
},
13+
"dependencies": {
14+
"googleapis": "^11.0.0"
15+
},
16+
"author": "Google, Inc.",
17+
"license": "Apache-2.0"
18+
}

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
"deps_datastore": "cd datastore; npm i; cd ../",
5555
"deps_debugger": "cd debugger; npm i; cd ../",
5656
"deps_functions": "cd functions/uuid; npm i; cd ../..",
57+
"deps_language": "cd language; npm i; cd ../",
5758
"deps_logging": "cd logging; npm i; cd ../",
5859
"deps_monitoring": "cd monitoring; npm i; cd ../",
5960
"deps_prediction": "cd prediction; npm i; cd ../",
@@ -64,7 +65,7 @@
6465
"deps_vision": "cd vision; npm i; cd ../",
6566
"lint": "semistandard \"**/*.js\"",
6667
"pretest_geddy": "cd appengine/geddy; npm i geddy; GEDDY_SECRET=config/secrets.json; [[ -f $GEDDY_SECRET ]] || echo '{}' > $GEDDY_SECRET && node node_modules/.bin/geddy gen secret; cd ../..;",
67-
"pretest": "npm run deps_trace; npm run deps_debugger; npm run deps_vision; npm run deps_computeengine; npm run deps_bigquery; npm run deps_datastore; npm run deps_monitoring; npm run deps_storage; npm run deps_pubsub; npm run deps_prediction; npm run deps_logging; npm run deps_functions; npm run deps_speech; npm run pretest_geddy;",
68+
"pretest": "npm run deps_language; npm run deps_trace; npm run deps_debugger; npm run deps_vision; npm run deps_computeengine; npm run deps_bigquery; npm run deps_datastore; npm run deps_monitoring; npm run deps_storage; npm run deps_pubsub; npm run deps_prediction; npm run deps_logging; npm run deps_functions; npm run deps_speech; npm run pretest_geddy;",
6869
"report": "nyc report --reporter=lcov | codecov",
6970
"report-html": "nyc report --reporter=html",
7071
"test": "npm run lint && npm run cover"

test/language/analyze.test.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// Copyright 2016, Google, Inc.
2+
// Licensed under the Apache License, Version 2.0 (the "License");
3+
// you may not use this file except in compliance with the License.
4+
// You may obtain a copy of the License at
5+
//
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
//
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
14+
'use strict';
15+
16+
var analyzeExample = require('../../language/analyze');
17+
18+
describe('language:analyze', function () {
19+
it('should analyze sentiment in text', function (done) {
20+
analyzeExample.main(
21+
'sentiment',
22+
'This gazinga pin is bad and it should feel bad',
23+
function (err, result) {
24+
assert(!err);
25+
assert(result);
26+
assert(result.documentSentiment);
27+
assert(result.documentSentiment.polarity < 0);
28+
done();
29+
}
30+
);
31+
});
32+
it('should analyze entities in text', function (done) {
33+
analyzeExample.main(
34+
'entities',
35+
'Mark Twain is the author of a book called Tom Sawyer',
36+
function (err, result) {
37+
assert(!err);
38+
assert(result);
39+
assert(result.entities && result.entities.length);
40+
assert(result.entities[0].name === 'Mark Twain');
41+
assert(result.entities[0].type === 'PERSON');
42+
done();
43+
}
44+
);
45+
});
46+
it('should analyze syntax in text', function (done) {
47+
analyzeExample.main(
48+
'syntax',
49+
'Betty bought a bit of bitter butter. But she said, "This butter\'s ' +
50+
'bitter! If I put it in my batter, it will make my batter bitter. If I ' +
51+
'buy some better butter - better than this bitter butter - it will ' +
52+
'make my batter better."',
53+
function (err, result) {
54+
assert(!err);
55+
assert(result);
56+
assert(result.sentences && result.sentences.length);
57+
assert(result.tokens && result.tokens.length > 5);
58+
done();
59+
}
60+
);
61+
});
62+
});

0 commit comments

Comments
 (0)