How to translate using your custom AutoML model in Python

If you’ve successfully trained your first custom AutoML neuronal translation model, the next step is to integrate it into your application.

Here’s a python3 utility class that easily allows you to translate using your custom model:

class GNTMAutoMLTranslationDriver(object):
    """
    Custom AutoML model translator.

    Usage example (be sure to use your own model here!):

    >>> translator = GNTMAutoMLTranslationDriver('myproject-101472', 'TRL455090968000816104449')
    >>> translator.translate("This is a translation test")
    """
    def __init__(self, project_id, model_id):
        self.client = automl_v1beta1.PredictionServiceClient()
        self._name = 'projects/{}/locations/us-central1/models/{}'.format(project_id, model_id)
    
    def translate(self, engl):
        payload = {'text_snippet': {'content': engl}}
        params = {}
        request = self.client.predict(self._name, payload, params)
        return request.payload[0].translation.translated_content.content

See the class documentation for a usage example. Most of the code is also present in the official AutoML example, but I had to figure out some parts for myself, e.g. how to extract the string from the protobuf (request.payload[0].translation.translated_content.content).

Also note that AutoML is currently in Beta and therefore the API might change without prior notice.