Skip to content

Commit

Permalink
Add support for AnalyzeEntitySentiment (#734)
Browse files Browse the repository at this point in the history
* Add support for AnalyzeEntitySentiment

* Add annotateText support

* Fix phpcs error
  • Loading branch information
michaelbausor authored and dwsupplee committed Nov 10, 2017
1 parent 2a3608c commit c9b0c79
Show file tree
Hide file tree
Showing 8 changed files with 195 additions and 5 deletions.
1 change: 1 addition & 0 deletions src/Language/Annotation.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
* Annotations are returned by
* {@see Google\Cloud\Language\LanguageClient::analyzeEntities()},
* {@see Google\Cloud\Language\LanguageClient::analyzeSentiment()},
* {@see Google\Cloud\Language\LanguageClient::analyzeEntitySentiment()},
* {@see Google\Cloud\Language\LanguageClient::analyzeSyntax()} and
* {@see Google\Cloud\Language\LanguageClient::annotateText()}.
*
Expand Down
6 changes: 6 additions & 0 deletions src/Language/Connection/ConnectionInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ public function analyzeEntities(array $args = []);
*/
public function analyzeSentiment(array $args = []);

/**
* @param array $args
* @return array
*/
public function analyzeEntitySentiment(array $args = []);

/**
* @param array $args
* @return array
Expand Down
9 changes: 9 additions & 0 deletions src/Language/Connection/Rest.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,15 @@ public function analyzeSentiment(array $args = [])
return $this->send('documents', 'analyzeSentiment', $args);
}

/**
* @param array $args
* @return array
*/
public function analyzeEntitySentiment(array $args = [])
{
return $this->send('documents', 'analyzeEntitySentiment', $args);
}

/**
* @param array $args
* @return array
Expand Down
66 changes: 63 additions & 3 deletions src/Language/LanguageClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ class LanguageClient
'syntax' => 'extractSyntax',
'entities' => 'extractEntities',
'sentiment' => 'extractDocumentSentiment',
'entitySentiment' => 'extractEntitySentiment',
'classify' => 'classifyText'
];

Expand Down Expand Up @@ -218,6 +219,65 @@ public function analyzeSentiment($content, array $options = [])
);
}

/**
* Finds entities in the text and analyzes sentiment associated with each
* entity and its mentions.
*
* Example:
* ```
* $annotation = $language->analyzeEntitySentiment('Google Cloud Platform is a powerful tool.');
* $entities = $annotation->entities();
*
* echo 'Entity name: ' . $entities[0]['name'] . PHP_EOL;
* if ($entities[0]['sentiment']['score'] > 0) {
* echo 'This is a positive message.';
* }
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/natural-language/docs/reference/rest/v1/documents/analyzeEntitySentiment Analyze Entity Sentiment API documentation
* @codingStandardsIgnoreEnd
*
* @param string|StorageObject $content The content to analyze. May be
* either a string of UTF-8 encoded content, a URI pointing to a
* Google Cloud Storage object in the format of
* `gs://{bucket-name}/{object-name}` or a
* {@see Google\Cloud\Storage\StorageObject}.
* @param array $options [optional] {
* Configuration options.
*
* @type bool $detectGcsUri When providing $content as a string, this
* flag determines whether or not to attempt to detect if the
* string represents a Google Cloud Storage URI in the format of
* `gs://{bucket-name}/{object-name}`. **Defaults to** `true`.
* @type string $type The document type. Acceptable values are
* `PLAIN_TEXT` or `HTML`. **Defaults to** `"PLAIN_TEXT"`.
* @type string $language The language of the document. Both ISO
* (e.g., en, es) and BCP-47 (e.g., en-US, es-ES) language codes
* are accepted. If no value is provided, the language will be
* detected by the service.
* @type string $encodingType The text encoding type used by the API to
* calculate offsets. Acceptable values are `"NONE"`, `"UTF8"`,
* `"UTF16"` and `"UTF32"`. **Defaults to** `"UTF8"`. Please note
* the following behaviors for the encoding type setting: `"NONE"`
* will return a value of "-1" for offsets. `"UTF8"` will
* return byte offsets. `"UTF16"` will return
* [code unit](http://unicode.org/glossary/#code_unit) offsets.
* `"UTF32"` will return
* [unicode character](http://unicode.org/glossary/#character)
* offsets.
* }
* @return Annotation
*/
public function analyzeEntitySentiment($content, array $options = [])
{
return new Annotation(
$this->connection->analyzeEntitySentiment(
$this->formatRequest($content, $options)
)
);
}

/**
* Analyzes the document and provides a full set of text annotations.
*
Expand Down Expand Up @@ -362,9 +422,9 @@ public function classifyText($content, array $options = [])
* string represents a Google Cloud Storage URI in the format of
* `gs://{bucket-name}/{object-name}`. **Defaults to** `true`.
* @type array $features Features to apply to the request. Valid values
* are `syntax`, `sentiment`, `entities`, and `classify`. If no
* features are provided the request will run with all four
* enabled.
* are `syntax`, `sentiment`, `entities`, `entitySentiment`, and
* `classify`. If no features are provided the request will run
* with all features enabled.
* @type string $type The document type. Acceptable values are
* `PLAIN_TEXT` or `HTML`. **Defaults to** `"PLAIN_TEXT"`.
* @type string $language The language of the document. Both ISO
Expand Down
26 changes: 26 additions & 0 deletions tests/snippets/Language/LanguageClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,32 @@ public function testAnalyzeSentiment()
$this->assertEquals("This is a positive message.", $res->output());
}

public function testAnalyzeEntitySentiment()
{
$this->connection->analyzeEntitySentiment(Argument::any())
->shouldBeCalled()
->willReturn([
'entities' => [
[
'name' => 'Google Cloud Platform',
'sentiment' => [
'score' => 1.0
]
]
]
]);

$this->client->___setProperty('connection', $this->connection->reveal());

$snippet = $this->snippetFromMethod(LanguageClient::class, 'analyzeEntitySentiment');
$snippet->addLocal('language', $this->client);

$res = $snippet->invoke();
$lines = explode(PHP_EOL, $res->output());
$this->assertEquals('Entity name: Google Cloud Platform', $lines[0]);
$this->assertEquals("This is a positive message.", $lines[1]);
}

public function testAnalyzeSyntax()
{
$this->connection->analyzeSyntax(Argument::any())
Expand Down
70 changes: 70 additions & 0 deletions tests/system/Language/AnalyzeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,76 @@ public function analyzeEntitiesProvider()
];
}

/**
* @dataProvider analyzeEntitySentimentProvider
*/
public function testAnalyzeEntitySentiment($text, $expectedEntities)
{
$result = self::$client->analyzeEntitySentiment($text);
$info = $result->info();

foreach ($expectedEntities as $expectedEntity) {
$exists = false;
foreach ($info['entities'] as $entity) {
if ($entity['name'] == $expectedEntity['name']) {
$exists = true;
$this->assertEquals($entity['type'], $expectedEntity['type']);
$this->assertEquals($entity['sentiment'], $expectedEntity['sentiment']);
break;
}
}
$this->assertTrue($exists);
}
}

public function analyzeEntitySentimentProvider()
{
return [
[
'Do you know the way to San Jose?',
[
[
'name' => 'San Jose',
'type' => 'LOCATION',
'sentiment' => [
'magnitude' => 0,
'score' => 0,
],
],
[
'name' => 'way',
'type' => 'OTHER',
'sentiment' => [
'magnitude' => 0,
'score' => 0,
],
],
]
],
[
"The road to San Jose is great!",
[
[
'name' => 'San Jose',
'type' => 'LOCATION',
'sentiment' => [
'magnitude' => 0.3,
'score' => 0.3,
],
],
[
'name' => 'road',
'type' => 'LOCATION',
'sentiment' => [
'magnitude' => 0.3,
'score' => 0.3,
],
],
]
]
];
}

public function testClassifyText()
{
$result = self::$client->classifyText(
Expand Down
1 change: 1 addition & 0 deletions tests/unit/Language/Connection/RestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ public function methodProvider()
return [
['analyzeSentiment'],
['analyzeEntities'],
['analyzeEntitySentiment'],
['analyzeSyntax'],
['annotateText'],
['classifyText']
Expand Down
21 changes: 19 additions & 2 deletions tests/unit/Language/LanguageClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,22 @@ public function testAnalyzeSentiment($options, $expectedOptions)
$this->assertInstanceOf(Annotation::class, $annotation);
}

/**
* @dataProvider analyzeDataProvider
*/
public function testAnalyzeEntitySentiment($options, $expectedOptions)
{
$content = $options['content'];
unset($options['content']);
$this->connection
->analyzeEntitySentiment($expectedOptions)
->willReturn([])
->shouldBeCalledTimes(1);
$this->client->setConnection($this->connection->reveal());
$annotation = $this->client->analyzeEntitySentiment($content, $options);
$this->assertInstanceOf(Annotation::class, $annotation);
}

/**
* @dataProvider analyzeDataProvider
*/
Expand Down Expand Up @@ -124,11 +140,12 @@ public function testAnnotateText($options, $expectedOptions)
{
$content = $options['content'];
unset($options['content']);
$options['features'] = ['syntax', 'entities', 'sentiment'];
$options['features'] = ['syntax', 'entities', 'sentiment', 'entitySentiment'];
$expectedOptions['features'] = [
'extractSyntax' => true,
'extractEntities' => true,
'extractDocumentSentiment' => true
'extractDocumentSentiment' => true,
'extractEntitySentiment' => true,
];
$this->connection
->annotateText($expectedOptions)
Expand Down

0 comments on commit c9b0c79

Please sign in to comment.