Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add sample for Natural Language 1.1 launch #352

Merged
merged 5 commits into from
Apr 21, 2017
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 98 additions & 3 deletions language/analyze.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ function analyzeSentimentOfText (text) {
// Detects the sentiment of the document
document.detectSentiment()
.then((results) => {
const sentiment = results[0];
const sentiment = results[1].documentSentiment;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it just that the first result is missing sentiment? I'm seeing that not all the entities returned have sentiment.

console.log(`Score: ${sentiment.score}`);
console.log(`Magnitude: ${sentiment.magnitude}`);
})
Expand Down Expand Up @@ -67,7 +67,7 @@ function analyzeSentimentInFile (bucketName, fileName) {
// Detects the sentiment of the document
document.detectSentiment()
.then((results) => {
const sentiment = results[0];
const sentiment = results[1].documentSentiment;
console.log(`Score: ${sentiment.score}`);
console.log(`Magnitude: ${sentiment.magnitude}`);
})
Expand All @@ -94,7 +94,7 @@ function analyzeEntitiesOfText (text) {
// Detects entities in the document
document.detectEntities()
.then((results) => {
const entities = results[0];
const entities = results[1].entities;

console.log('Entities:');
entities.forEach((entity) => {
Expand Down Expand Up @@ -215,6 +215,87 @@ function analyzeSyntaxInFile (bucketName, fileName) {
// [END language_syntax_file]
}

function analyzeEntitySentimentOfText (text) {
// [START language_entity_sentiment_string]
// Imports the Google Cloud client library
const Language = require('@google-cloud/language').v1beta2();

// Instantiates a client
const language = Language.languageServiceClient();

// The text to analyze, e.g. "Hello, world!"
// const text = 'Hello, world!';

// Configure a request containing a string
const request = {
document: {
type: 'PLAIN_TEXT',
content: text
}
};

// Detects sentiment of entities in the document
language.analyzeEntitySentiment(request)
.then((results) => {
const entities = results[0].entities;

console.log(`Entities and sentiments:`)
entities.forEach((entity) => {
console.log(` Name: ${entity.name}`);
console.log(` Type: ${entity.type}`);
console.log(` Score: ${entity.sentiment.score}`);
console.log(` Magnitude: ${entity.sentiment.magnitude}`);
});
})
.catch((err) => {
console.error('ERROR:', err);
});
// [END language_entity_sentiment_string]
}

function analyzeEntitySentimentInFile (bucketName, fileName) {
// [START language_entity_sentiment_file]
// Imports the Google Cloud client libraries
const Language = require('@google-cloud/language').v1beta2();
const Storage = require('@google-cloud/storage');

// Instantiates the clients
const language = Language.languageServiceClient();
const storage = Storage();

// The name of the bucket where the file resides, e.g. "my-bucket"
// const bucketName = 'my-bucket';

// The name of the file to analyze, e.g. "file.txt"
// const fileName = 'file.txt';

// Configure a request containing a string
const request = {
document: {
type: 'PLAIN_TEXT',
gcsContentUri: `gs://${bucketName}/${fileName}`
}
};

// Detects sentiment of entities in the document
language.analyzeEntitySentiment(request)
.then((results) => {
const entities = results[0].entities;

console.log(`Entities and sentiments:`)
entities.forEach((entity) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't forget the mentions in entity sentiment:

from Python:

    for entity in result.entities:
        print('Mentions: ')
        print(u'Name: "{}"'.format(entity.name))
        for mention in entity.mentions:
            print(u'  Begin Offset : {}'.format(mention.text.begin_offset))
            print(u'  Content : {}'.format(mention.text.content))
            print(u'  Magnitude : {}'.format(mention.sentiment.magnitude))
            print(u'  Sentiment : {}'.format(mention.sentiment.score))
            print(u'  Type : {}'.format(mention.type))
        print(u'Salience: {}'.format(entity.salience))
        print(u'Sentiment: {}\n'.format(entity.sentiment))

console.log(` Name: ${entity.name}`);
console.log(` Type: ${entity.type}`);
console.log(` Score: ${entity.sentiment.score}`);
console.log(` Magnitude: ${entity.sentiment.magnitude}`);
});
})
.catch((err) => {
console.error('ERROR:', err);
});
// [END language_entity_sentiment_file]
}

require(`yargs`)
.demand(1)
.command(
Expand Down Expand Up @@ -253,12 +334,26 @@ require(`yargs`)
{},
(opts) => analyzeSyntaxInFile(opts.bucketName, opts.fileName)
)
.command(
`entity-sentiment-text <text>`,
`Detects sentiment of the entities in a string.`,
{},
(opts) => analyzeEntitySentimentOfText(opts.text)
)
.command(
`entity-sentiment-file <bucketName> <fileName>`,
`Detects sentiment of the entities in a file in Google Cloud Storage.`,
{},
(opts) => analyzeEntitySentimentInFile(opts.bucketName, opts.fileName)
)
.example(`node $0 sentiment-text "President Obama is speaking at the White House."`)
.example(`node $0 sentiment-file my-bucket file.txt`, `Detects sentiment in gs://my-bucket/file.txt`)
.example(`node $0 entities-text "President Obama is speaking at the White House."`)
.example(`node $0 entities-file my-bucket file.txt`, `Detects entities in gs://my-bucket/file.txt`)
.example(`node $0 syntax-text "President Obama is speaking at the White House."`)
.example(`node $0 syntax-file my-bucket file.txt`, `Detects syntax in gs://my-bucket/file.txt`)
.example(`node $0 entity-sentiment-text "President Obama is speaking at the White House."`)
.example(`node $0 entity-sentiment-file my-bucket file.txt`, `Detects sentiment of entities in gs://my-bucket/file.txt`)
.wrap(120)
.recommendCommands()
.epilogue(`For more information, see https://cloud.google.com/natural-language/docs`)
Expand Down
20 changes: 18 additions & 2 deletions language/system-test/analyze.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,30 @@ test(`should analyze syntax in text`, async (t) => {
t.true(output.includes(`Parts of speech:`));
t.true(output.includes(`NOUN:`));
t.true(output.includes(`President`));
t.true(output.includes(`NOUN:`));
t.true(output.includes(`Obama`));
});

test('should analyze syntax in a file', async (t) => {
const output = await runAsync(`${cmd} syntax-file ${bucketName} ${fileName}`, cwd);
t.true(output.includes(`NOUN:`));
t.true(output.includes(`President`));
t.true(output.includes(`NOUN:`));
t.true(output.includes(`Obama`));
});

test(`should analyze entity sentiment in text`, async (t) => {
const output = await runAsync(`${cmd} entity-sentiment-text "${text}"`, cwd);
t.true(output.includes(`Entities and sentiments:`));
t.true(output.includes(`Obama`));
t.true(output.includes(`PERSON`));
t.true(output.includes(`Score: 0`));
t.true(output.includes(`Magnitude: 0`));
});

test('should analyze entity sentiment in a file', async (t) => {
const output = await runAsync(`${cmd} entity-sentiment-file ${bucketName} ${fileName}`, cwd);
t.true(output.includes(`Entities and sentiments:`));
t.true(output.includes(`Obama`));
t.true(output.includes(`PERSON`));
t.true(output.includes(`Score: 0`));
t.true(output.includes(`Magnitude: 0`));
});