Skip to content

Commit

Permalink
Adding Entity.from_api_repr() helper for language.
Browse files Browse the repository at this point in the history
  • Loading branch information
dhermes committed Aug 23, 2016
1 parent 1e5c6dd commit 7dbdefb
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
19 changes: 18 additions & 1 deletion gcloud/language/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ class EntityType(object):
"""Other entity type (i.e. known but not classified)."""



class Entity(object):
"""A Google Cloud Natural Language API entity.
Expand Down Expand Up @@ -82,3 +81,21 @@ def __init__(self, name, entity_type, metadata, salience, mentions):
self.metadata = metadata
self.salience = salience
self.mentions = mentions

@classmethod
def from_api_repr(cls, payload):
"""Convert an Entity from the JSON API into an :class:`Entity`.
:param payload: dict
:type payload: The value from the backend.
:rtype: :class:`Entity`
:returns: The entity parsed from the API representation.
"""
name = payload['name']
entity_type = payload['type']
metadata = payload['metadata']
salience = payload['salience']
mentions = [value['text']['content']
for value in payload['mentions']]
return cls(name, entity_type, metadata, salience, mentions)
27 changes: 27 additions & 0 deletions gcloud/language/test_entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,30 @@ def test_constructor_defaults(self):
self.assertEqual(entity.metadata, metadata)
self.assertEqual(entity.salience, salience)
self.assertEqual(entity.mentions, mentions)

def test_from_api_repr(self):
klass = self._getTargetClass()
name = 'Italy'
entity_type = 'LOCATION'
salience = 0.223
metadata = {'wikipedia_url': 'http://en.wikipedia.org/wiki/Italy'}
mention1 = 'Italy'
mention2 = 'To Italy'
mention3 = 'From Italy'
payload = {
'name': name,
'type': entity_type,
'salience': salience,
'metadata': metadata,
'mentions': [
{'text': {'content': mention1}},
{'text': {'content': mention2}},
{'text': {'content': mention3}},
],
}
entity = klass.from_api_repr(payload)
self.assertEqual(entity.name, name)
self.assertEqual(entity.entity_type, entity_type)
self.assertEqual(entity.salience, salience)
self.assertEqual(entity.metadata, metadata)
self.assertEqual(entity.mentions, [mention1, mention2, mention3])

0 comments on commit 7dbdefb

Please sign in to comment.