Skip to content

Commit 7dbdefb

Browse files
committed
Adding Entity.from_api_repr() helper for language.
1 parent 1e5c6dd commit 7dbdefb

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

gcloud/language/entity.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@ class EntityType(object):
4646
"""Other entity type (i.e. known but not classified)."""
4747

4848

49-
5049
class Entity(object):
5150
"""A Google Cloud Natural Language API entity.
5251
@@ -82,3 +81,21 @@ def __init__(self, name, entity_type, metadata, salience, mentions):
8281
self.metadata = metadata
8382
self.salience = salience
8483
self.mentions = mentions
84+
85+
@classmethod
86+
def from_api_repr(cls, payload):
87+
"""Convert an Entity from the JSON API into an :class:`Entity`.
88+
89+
:param payload: dict
90+
:type payload: The value from the backend.
91+
92+
:rtype: :class:`Entity`
93+
:returns: The entity parsed from the API representation.
94+
"""
95+
name = payload['name']
96+
entity_type = payload['type']
97+
metadata = payload['metadata']
98+
salience = payload['salience']
99+
mentions = [value['text']['content']
100+
for value in payload['mentions']]
101+
return cls(name, entity_type, metadata, salience, mentions)

gcloud/language/test_entity.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,30 @@ def test_constructor_defaults(self):
3737
self.assertEqual(entity.metadata, metadata)
3838
self.assertEqual(entity.salience, salience)
3939
self.assertEqual(entity.mentions, mentions)
40+
41+
def test_from_api_repr(self):
42+
klass = self._getTargetClass()
43+
name = 'Italy'
44+
entity_type = 'LOCATION'
45+
salience = 0.223
46+
metadata = {'wikipedia_url': 'http://en.wikipedia.org/wiki/Italy'}
47+
mention1 = 'Italy'
48+
mention2 = 'To Italy'
49+
mention3 = 'From Italy'
50+
payload = {
51+
'name': name,
52+
'type': entity_type,
53+
'salience': salience,
54+
'metadata': metadata,
55+
'mentions': [
56+
{'text': {'content': mention1}},
57+
{'text': {'content': mention2}},
58+
{'text': {'content': mention3}},
59+
],
60+
}
61+
entity = klass.from_api_repr(payload)
62+
self.assertEqual(entity.name, name)
63+
self.assertEqual(entity.entity_type, entity_type)
64+
self.assertEqual(entity.salience, salience)
65+
self.assertEqual(entity.metadata, metadata)
66+
self.assertEqual(entity.mentions, [mention1, mention2, mention3])

0 commit comments

Comments
 (0)