Google Translation API

We will show how to use Google Translation API using Google Colab.

Prerequisites

  • account in Google Cloud Platform (GCP)
  • service account key
  • enable Google Cloud Translation API
  • python package – from google.cloud import translate_v2

Steps

  • upload your service account key to your Google Colab notebook
  • set up environment variable called GOOGLE_APPLICATION_CREDENTIALS
  • write a simple python code

Code to translate text

# Imports the Google Cloud client library
import os    
from google.cloud import translate_v2 as translate

credential_path = "/content/service_key.json"
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credential_path

# Instantiates a client
translate_client = translate.Client()

# The text to translate
text = u'Hello world!'
# The target language
target = 'bn' # bangla

# Translates some text into Bangla
translation = translate_client.translate(
    text,
    target_language=target)

print(u'Text: {}'.format(text))
print(u'Translation: {}'.format(translation['translatedText']))

Translating a HTML file

# reading a file and translate it in Bangla
with open("/content/sample_data/README.md") as f:
    html_content = f.read()

html_english = translate_client.translate(html_content, target_language='bn', format_='html')
print(html_english)

# using a class
from google.cloud import translate_v2
class Translate(object):
    def __init__(self, text, source_language='bn'):
        self.text = text
        self.source_language = source_language
        self.translate_client = translate_v2.Client()
    def translator(self):
        translated = self.translate_client.translate(
            self.text,
            source_language = self.source_language
            )
        return translated['translatedText']
translator = Translate("ওহে বিশ্ব!")
print(translator.translator())