Build a language translator using Python and googletrans

Photo by Chris Ried on Unsplash

Build a language translator using Python and googletrans

·

5 min read

Know only one language? Don't worry, in this post we will learn how to build our own translator so that we don't have to look for a translator to understand the language we are not familiar with. Having a translation device when we travel to a new place where where we don't speak their native language will help us communicate with the locals and ask for their help.

Google translate is a free service that we can use to translate words, phrases or sentences to another language. We are going to use the googletrans Python library to translate between languages. Currently, it supports 107 languages.

Create a virtual environment if you want to install the packages separately inside a particular environment:

$ py -3 -m venv env
$ .\env\Scripts\activate
  1. Installation

We will begin by installing the google trans library:

$ pip install googletrans==4.0.0-rc1
  1. Code Implementation

i. Create a file named 'Translate.py' ii. Import the library

import googletrans  # In order to use google trans library
from googletrans import Translator

ii. Create and instance of googletrans

t = Translator()

iii. Store all the supported languages in a variable

supported_langs = googletrans.LANGUAGES   # This will be a python dictionary

iv. Let's try to print the supported languages

# Print all the languages in 
print('Supported languages: ')
for key, value in supported_langs.items():
    print(key, ':', value)

v. We will create a function to get the input which will be the source language. This language will be translated to another language

# Get the source language
def get_source():
    source_lang = input('Source language: ')

    # is source_lang in lanuguage keys
    if source_lang in supported_langs.keys():
        return source_lang

    # Check if it is present in language values
    for key, value in supported_langs.items():
        if source_lang == value:   
            return key

    else:
        return ''

vi. Now we will create another function which will get the target language. The text we enter will be translated to this language.

# Get destination language
def get_dest():
    dest_lang = input('Translate to: ')    

    # if dest_lang in language key
    if dest_lang in supported_langs.keys():
        return dest_lang

    # Check if it is present in language values
    for key, value in supported_langs.items():
        if dest_lang == value:  
            return key

    else:
        return ''

vii. Create a function 'translate()' which will be used for translating the text by checking the source and destination language.

Note: Notice the commented print() functions, if you want to check what it prints in between, you can check by removing the comments.

def translate():
    print('Choose the language from the supported languages')
    source_lang = get_source()
    # print(source_lang)

    dest_lang = get_dest()
    # print(dest_lang)

    text = input("Enter your Text: ")
    print("Text to be translated: "+ text)

    # Let's print the language of input text
    input_text = t.translate(text)
    s = input_text.src
    print('Entered text is in:', s) 

    # We can obtain the attributes with following
    # print(result.src)
    # print(result.dest)
    # print(result.origin)
    # print(result.text)
    # print(result.pronunciation)


    # The get_source() or get_dest() returns null means inputs are invalid which means the language is unsupported
    if source_lang == '' or dest_lang == '':
        print("Invalid input...")

    try:
        if source_lang and dest_lang:  
            # Using translate() method which requires
            # three arguments, 1st the sentence which needs to be translated 
            # 2nd source language
            # and 3rd to which we need to translate in
            result = t.translate(text, src=source_lang, dest=dest_lang)   # Translate the text 

            # Ensure the input to be entered using the language specified
            if source_lang == s:
                print(f'Translated text to {supported_langs[dest_lang]}: {result.text}')
                print(f"Pronunciation in {supported_langs[dest_lang]}: {result.pronunciation}")

            else:
                print('Enter in ', supported_langs[source_lang])

    except:
        print("Unable to understand the input...")

viii. Bingo!! it's our translator, time to run our app:

if __name__=='__main__':
    translate()  # Run it continuously
    while True:
        q = input('Do you want to continue? (y/n): ')
        if q == 'n':
            break
        else:
            translate()

Our final code is as follows:

import googletrans  # In order to use google trans library
from googletrans import Translator

t = Translator()

# Store all the supported languages in a variable
supported_langs = googletrans.LANGUAGES   # This will be a python dictionary

# Print all the languages in 
print('Supported languages: ')
for key, value in supported_langs.items():
    print(key, ':', value)

# Get the source language
def get_source():
    source_lang = input('Source language: ')

    # is source_lang in lanuguage keys
    if source_lang in supported_langs.keys():
        return source_lang

    # Check if it is present in language values
    for key, value in supported_langs.items():
        if source_lang == value:  
            return key

    else:
        return ''

# Get destination language
def get_dest():
    dest_lang = input('Translate to: ')    

    # if dest_lang in language key
    if dest_lang in supported_langs.keys():
        return dest_lang

    # Check if it is present in language values
    for key, value in supported_langs.items():
        if dest_lang == value:   
            return key

    else:
        return ''

def translate():
    print('Choose the language from the supported languages')
    source_lang = get_source()
    # print(source_lang)

    dest_lang = get_dest()
    # print(dest_lang)

    text = input("Enter your Text: ")
    print("Text to be translated: "+ text)

    # Let's print the language of input text
    input_text = t.translate(text)
    s = input_text.src
    print('Entered text is in:', s) 

    # We can obtain the attributes with following
    # print(result.src)
    # print(result.dest)
    # print(result.origin)
    # print(result.text)
    # print(result.pronunciation)


    # The get_source() or get_dest() returns null means inputs are invalid which means the language is unsupported
    if source_lang == '' or dest_lang == '':
        print("Invalid input...")

    try:
        if source_lang and dest_lang:  
            # Using translate() method which requires
            # three arguments, 1st the sentence which needs to be translated 
            # 2nd source language
            # and 3rd to which we need to translate in
            result = t.translate(text, src=source_lang, dest=dest_lang)   # Translate the text 

            # Ensure the input to be entered using the language specified
            if source_lang == s:
                print(f'Translated text to {supported_langs[dest_lang]}: {result.text}')
                print(f"Pronunciation in {supported_langs[dest_lang]}: {result.pronunciation}")

            else:
                print('Enter in ', supported_langs[source_lang])

    except:
        print("Unable to understand the input...")



if __name__=='__main__':
    translate()  # Run it continuously
    while True:
        q = input('Do you want to continue? (y/n): ')
        if q == 'n':
            break
        else:
            translate()

GitHub

It's not the end, there are a lot of fun waiting, let us keep on taking our translator to next level. You may explore further. Thank you for reading this post and my apologies for the bugs in the code.