Translation API - Google Cloud Tutorial




Welcome to part 5 of the Google Cloud tutorial series, in this tutorial we're going to cover the Translation API.

As usual, you first need to enable this, and of course you need to have your credentials all set up (see part 2 if you haven't done this).

The translation API allows us to take any (well, just about) language and translate it into a target language. The beauty of this is that you don't need to know the language that you're attempting to translate, you just need to know what language you want it to be in.

For the target language, you need to use the ISO 639-1 code for it. For me, I will be using en, for English.

Now, as usual, we will define the client like so: translate_client = translate.Client(), but, rather than detections and attributes, our return is just a typical json format. We can make a translation function like so:

# -*- coding: utf-8 -*- 
from google.cloud import translate

def translate_text(text,target='en'):
    """
    Target must be an ISO 639-1 language code.
    https://cloud.google.com/translate/docs/languages
    """
    translate_client = translate.Client()
    result = translate_client.translate(
        text,
        target_language=target)

    print(u'Text: {}'.format(result['input']))
    print(u'Translation: {}'.format(result['translatedText']))
    print(u'Detected source language: {}'.format(
        result['detectedSourceLanguage']))

Then use it:

example_text ='''Hola saludos desde Colombia excelentes tutoriales me gustaría poder por lo menos tener los subtitulos ene español ...excelente gracias por compartir tus conocimientos'''
translate_text(example_text.decode('utf-8'),target='en')

output:

Text: Hola saludos desde Colombia excelentes tutoriales me gustaría poder por lo menos tener los subtitulos ene español ...excelente gracias por compartir tus conocimientos
Translation: Hello greetings from Colombia excellent tutorials I wish I could at least have Spanish subtitles ene ... excellent thanks for sharing your knowledge
Detected source language: es

The next tutorial:





  • Intro and creating a virtual machine - Google Cloud Tutorial
  • Setting up API and Vision Intro - Google Cloud Tutorial
  • Vision API continued - Google Cloud Tutorial
  • Natural Language API - Google Cloud Tutorial
  • Translation API - Google Cloud Tutorial