From 7dbdefb99124d7e92d4b80901d65ef990b4ac120 Mon Sep 17 00:00:00 2001 From: Danny Hermes Date: Mon, 22 Aug 2016 15:59:14 -0700 Subject: [PATCH] Adding Entity.from_api_repr() helper for language. --- gcloud/language/entity.py | 19 ++++++++++++++++++- gcloud/language/test_entity.py | 27 +++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/gcloud/language/entity.py b/gcloud/language/entity.py index 2c4a16648b257..c7254c06dc16a 100644 --- a/gcloud/language/entity.py +++ b/gcloud/language/entity.py @@ -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. @@ -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) diff --git a/gcloud/language/test_entity.py b/gcloud/language/test_entity.py index 3ba644669de1e..7eab34a401012 100644 --- a/gcloud/language/test_entity.py +++ b/gcloud/language/test_entity.py @@ -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])