In our interconnected world, language barriers can often hinder communication. To address this, we can create an AI-based language translator using Python's Tkinter library for the graphical user interface (GUI) and the googletrans library for translation services. In this article, we will walk through the entire process of building a simple language translator application.

Prerequisites

Ensure you have the following before starting.

  1. Python Installed: Make sure you have Python 3.x installed on your machine.
  2. Required Libraries: You will need to install the googletrans library and Tkinter (which comes with most Python installations). You can install the googletrans library using pip.
    pip install googletrans==4.0.0-rc1

Code Overview

Let's examine the code step by step, breaking down each section for clarity.

Importing Necessary Libraries

import tkinter as tk
from tkinter import ttk, messagebox
from googletrans import Translator, LANGUAGES

Here, we import,

Initializing the Translator

# Initialize the Google Translator
translator = Translator()

We create an instance of the Translator class from googletrans, which we will use for translating text.

Supported Languages

# Supported target languages and their codes
supported_languages = {
    'Hindi': 'hi',
    'Bengali': 'bn',
    'French': 'fr',
    'German': 'de'
}

We define a dictionary, supported_languages, which maps the names of languages to their respective language codes. This enables us to translate text to specific languages easily.

Translation Function

# Function to perform translation using googletrans
def translate(text, target_lang):
    try:
        # Translate the text
        translated = translator.translate(text, dest=target_lang)
        return translated.text
    except Exception as e:
        messagebox.showerror("Error", f"Translation error: {e}")
        return None

The translate function takes two parameters: the text to translate and the target language code. It attempts to translate the text and returns the translated string. If an error occurs, it displays an error message to the user.

Handling the Translation Process

# Function to handle the translation process
def handle_translation(target_lang):
    text = input_text.get("1.0", tk.END).strip()
    
    if not text:
        messagebox.showwarning("Input Error", "Please enter some text to translate.")
        return
    
    # Auto-detect the language of the input text
    detected_lang = translator.detect(text).lang

    if detected_lang not in ['en', 'hi', 'bn', 'fr', 'de']:
        messagebox.showwarning("Unsupported Language", f"The detected language '{detected_lang}' is not supported.")
        return

    if detected_lang == target_lang:
        messagebox.showinfo("Info", "Source and target languages are the same. No translation needed.")
        return

    # Translate text
    translation = translate(text, target_lang)
    if translation:
        output_text.delete("1.0", tk.END)
        output_text.insert(tk.END, translation)

In this function.

Custom Language Selection

# Function to handle the selection of a custom language
def select_custom_language():
    # Create a new top-level window for selecting a language
    lang_window = tk.Toplevel(root)
    lang_window.title("Select Language")

    # Language Selection Dropdown
    language_options = list(LANGUAGES.values())
    lang_var = tk.StringVar()
    
    lang_label = ttk.Label(lang_window, text="Select the language:")
    lang_label.pack(pady=10)

    lang_combo = ttk.Combobox(lang_window, values=language_options)
    lang_combo.pack(pady=10)

    def translate_custom_language():
        selected_language = lang_combo.get()
        lang_code = [code for code, lang in LANGUAGES.items() if lang == selected_language][0]

        handle_translation(lang_code)
        lang_window.destroy()

    # Translate Button in custom language window
    translate_button = ttk.Button(lang_window, text="Translate", command=translate_custom_language)
    translate_button.pack(pady=10)

This function allows users to select a custom language.

Creating the GUI

# Create the GUI
root = tk.Tk()
root.title("Subham's AI Language Translator")
root.geometry("500x400")

# Input Text Label
input_label = ttk.Label(root, text="Enter text to translate:")
input_label.pack(pady=10)

# Input Text Box
input_text = tk.Text(root, height=5, width=50)
input_text.pack(pady=10)

# Language Selection Buttons
button_frame = ttk.Frame(root)
button_frame.pack(pady=10)

def create_language_button(lang_name, lang_code):
    button = ttk.Button(button_frame, text=f"Translate to {lang_name}", command=lambda: handle_translation(lang_code))
    button.pack(side=tk.LEFT, padx=5)

# Create buttons for each supported language
for lang_name, lang_code in supported_languages.items():
    create_language_button(lang_name, lang_code)

# Other Language Button
other_language_button = ttk.Button(root, text="Other Language", command=select_custom_language)
other_language_button.pack(pady=10)

# Output Text Label
output_label = ttk.Label(root, text="Translated text:")
output_label.pack(pady=10)

# Output Text Box
output_text = tk.Text(root, height=5, width=50)
output_text.pack(pady=10)

# Start the main loop
root.mainloop()

In this section, we build the main GUI.

Full Code

import tkinter as tk
from tkinter import ttk, messagebox
from googletrans import Translator, LANGUAGES

# Initialize the Google Translator
translator = Translator()

# Supported target languages and their codes
supported_languages = {
    'Hindi': 'hi',
    'Bengali': 'bn',
    'French': 'fr',
    'German': 'de'
}

# Function to perform translation using googletrans
def translate(text, target_lang):
    try:
        # Translate the text
        translated = translator.translate(text, dest=target_lang)
        return translated.text
    except Exception as e:
        messagebox.showerror("Error", f"Translation error: {e}")
        return None

# Function to handle the translation process
def handle_translation(target_lang):
    text = input_text.get("1.0", tk.END).strip()
    
    if not text:
        messagebox.showwarning("Input Error", "Please enter some text to translate.")
        return
    
    # Auto-detect the language of the input text
    detected_lang = translator.detect(text).lang

    if detected_lang not in ['en', 'hi', 'bn', 'fr', 'de']:
        messagebox.showwarning("Unsupported Language", f"The detected language '{detected_lang}' is not supported.")
        return

    if detected_lang == target_lang:
        messagebox.showinfo("Info", "Source and target languages are the same. No translation needed.")
        return

    # Translate text
    translation = translate(text, target_lang)
    if translation:
        output_text.delete("1.0", tk.END)
        output_text.insert(tk.END, translation)

# Function to handle the selection of a custom language
def select_custom_language():
    # Create a new top-level window for selecting a language
    lang_window = tk.Toplevel(root)
    lang_window.title("Select Language")

    # Language Selection Dropdown
    language_options = list(LANGUAGES.values())
    lang_var = tk.StringVar()
    
    lang_label = ttk.Label(lang_window, text="Select the language:")
    lang_label.pack(pady=10)

    lang_combo = ttk.Combobox(lang_window, values=language_options)
    lang_combo.pack(pady=10)

    def translate_custom_language():
        selected_language = lang_combo.get()
        lang_code = [code for code, lang in LANGUAGES.items() if lang == selected_language][0]

        handle_translation(lang_code)
        lang_window.destroy()

    # Translate Button in custom language window
    translate_button = ttk.Button(lang_window, text="Translate", command=translate_custom_language)
    translate_button.pack(pady=10)

# Create the GUI
root = tk.Tk()
root.title("Subham's AI Language Translator")
root.geometry("500x400")

# Input Text Label
input_label = ttk.Label(root, text="Enter text to translate:")
input_label.pack(pady=10)

# Input Text Box
input_text = tk.Text(root, height=5, width=50)
input_text.pack(pady=10)

# Language Selection Buttons
button_frame = ttk.Frame(root)
button_frame.pack(pady=10)

def create_language_button(lang_name, lang_code):
    button = ttk.Button(button_frame, text=f"Translate to {lang_name}", command=lambda: handle_translation(lang_code))
    button.pack(side=tk.LEFT, padx=5)

# Create buttons for each supported language
for lang_name, lang_code in supported_languages.items():
    create_language_button(lang_name, lang_code)

# Other Language Button
other_language_button = ttk.Button(root, text="Other Language", command=select_custom_language)
other_language_button.pack(pady=10)

# Output Text Label
output_label = ttk.Label(root, text="Translated text:")
output_label.pack(pady=10)

# Output Text Box
output_text = tk.Text(root, height=5, width=50)
output_text.pack(pady=10)

# Start the main loop
root.mainloop()

Output

Text to translate

Conclusion

This AI-Language Translator application provides a straightforward interface for translating text between several languages. By using Tkinter for the GUI and Googletrans for the translation functionality, you can expand this basic framework to include additional features like speech recognition, saving translations, or even integrating it into a web application.