Home » Tutorials » How to Translate Languages with Flask in Python

How to Translate Languages with Flask in Python

In our previous Flask tutorials, we learned how to display web pages with Flask and handle user inputs. Today, we’re going to add a cool feature to our Flask app by using the googletrans library. Imagine typing in English and getting it back in Spanish, French, or any language you fancy, right on your screen.

In this tutorial, you’ll learn how to create a dynamic translation application that lets users input text in one language and receive translations in another, right in their browser. Ready to jump in? Let’s make our Flask project speak the language of the world!

Table of Contents

Before We Start

Make sure to create a ‘templates‘ file on the same file where your ‘app.py‘ is, in other words like this :

Necessary Libraries

In order for this code to function properly, you need to install the Flask and googletrans libraries via the terminal or your command prompt:

$ pip install flask 
$ pip install googletrans==4.0.0-rc1

Learn also:

Imports

from flask import Flask, render_template, request
from googletrans import Translator, LANGUAGES
  • We start by importing the Flask class from flask module to get our web app rolling.
  • Then, we pick up render_template to make our web pages look cool with HTML magic.
  • We also import the request feature to catch what users send our way (it gives us access to request data).
  • Next, we pull in the Translator from googletrans to knock down language barriers (Enables interactive, real-time translations).
  • And lastly, we grab a big list of languages by importing LANGUAGES so everyone can choose their favorite.

This mix of tools and tricks is our recipe for a friendly, world-ready web app.

Initializing Flask App and Translator Object

After importing the required libraries and modules, we begin by customizing our Flask class by creating an instance and making sure that Flask remembers its name.

app = Flask(__name__)

Then we initialize the Translator object for our translation.

translator = Translator()

Defining Routes

As we all know routes are particular URL patterns that allow the user to go to different pages or perform specific tasks in a browser. In this code, we have two routes:

Index Route

This route is the home page of our Google Translator app, as for how this page is displayed is very simple, basically our Flask application calls the index() function that will retrieve the results from the “index.html” template which will include a list of languages to choose from using the LANGUAGES dictionary.

All in all this route allows the user access to the home webpage.

@app.route('/')
def index():
   return render_template('index.html', languages=LANGUAGES)

Result Route

This route is where the translation result is shown, how that works is very easy:

First, it waits for the user to enter the text they want to translate, then once they perform the translate request (POST request) with the text that is sent to the “/translate” URL, the Second step begins, here Flask will call the translate () function which will extract the text submitted by the user as well as the source and target languages. Then in the third step, it will translate the text with Google Translate API.

Lastly, it will display the result by rendering the “index.html” template.

@app.route('/translate', methods=['POST'])
def translate():
   text = request.form['text']
   source_lang = request.form['source_lang']
   target_lang = request.form['target_lang']


   # Translate the text from the source language to the target language
   translated_text = translator.translate(text, src=source_lang, dest=target_lang).text


   return render_template('index.html', text=text, translated_text=translated_text, source_lang=LANGUAGES[source_lang],
                          target_lang=LANGUAGES[target_lang], languages=LANGUAGES)

Running the Flask Application

This section ensures the app runs directly and, not as an imported module in which case it would not function properly. It also enables debugging, allowing you to make changes in the code while it’s still running and the results will appear on the webpage by simply refreshing it.

However, it’s crucial to turn off debugging to prevent potential security breaches, as leaving it on can expose sensitive application data and vulnerabilities to hackers.

if __name__ == '__main__':
   app.run(debug=True)

Full Code

from flask import Flask, render_template, request
from googletrans import Translator, LANGUAGES


app = Flask(__name__)
translator = Translator()


@app.route('/')
def index():
   return render_template('index.html', languages=LANGUAGES)


@app.route('/translate', methods=['POST'])
def translate():
   text = request.form['text']
   source_lang = request.form['source_lang']
   target_lang = request.form['target_lang']


   # Translate the text from the source language to the target language
   translated_text = translator.translate(text, src=source_lang, dest=target_lang).text


   return render_template('index.html', text=text, translated_text=translated_text, source_lang=LANGUAGES[source_lang],
                          target_lang=LANGUAGES[target_lang], languages=LANGUAGES)


if __name__ == '__main__':
   app.run(debug=True)

Index HTML

<!DOCTYPE html>
<html>
<head>
  <title>Google Translator - The Pycodes</title>
  <style>
      body {
          font-family: Arial, sans-serif;
          margin: 0;
          padding: 0;
          background-color: #f5f5f5;
          display: flex;
          justify-content: center;
          align-items: center;
          height: 100vh;
      }
      .container {
          background-color: #fff;
          padding: 20px;
          border-radius: 10px;
          box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
          max-width: 500px;
          width: 100%;
          text-align: center;
      }
      h1 {
          margin-top: 0;
          color: #333;
      }
      input[type="text"], select, textarea {
          width: 100%;
          padding: 10px;
          margin-bottom: 10px;
          border: 1px solid #ccc;
          border-radius: 5px;
          box-sizing: border-box;
      }
      input[type="submit"] {
          background-color: #4CAF50;
          color: white;
          padding: 10px 20px;
          border: none;
          border-radius: 5px;
          cursor: pointer;
      }
      input[type="submit"]:hover {
          background-color: #45a049;
      }
      .result {
          margin-top: 20px;
      }
  </style>
</head>
<body>
  <div class="container">
      <h1>The Pycodes</h1>
      <h1>Google Translator</h1>
      <form action="/translate" method="post">
          <input type="text" name="text" placeholder="Enter text" required><br>
          <select name="source_lang" required>
              <option value="" disabled selected>Select Source Language</option>
              {% for code, lang in languages.items() %}
                  <option value="{{ code }}">{{ lang }}</option>
              {% endfor %}
          </select><br>
          <select name="target_lang" required>
              <option value="" disabled selected>Select Target Language</option>
              {% for code, lang in languages.items() %}
                  <option value="{{ code }}">{{ lang }}</option>
              {% endfor %}
          </select><br>
          <input type="submit" value="Translate">
      </form>
      <div class="result">
          {% if translated_text %}
          <p><strong>Original Text ({{ source_lang }}):</strong> {{ text }}</p>
          <p><strong>Translated Text ({{ target_lang }}):</strong> {{ translated_text }}</p>
          {% endif %}
      </div>
  </div>
</body>
</html>

HTML Structure and Title:

This part specifies that this document is an HTML, as well as sets the standard HTML elements: html, head, and body. And also sets up the title of the web page.

<!DOCTYPE html>
<html>
<head>
  <title>Google Translator - The Pycodes</title>

Cascading Style Sheets:

CSS is a language that allows us to develop aesthetically appealing and responsive web pages. Here we used it to define the appearance of the web page for our app such as font, margin, padding, background color, aligned content as well as border radius as well as styling the Heading and paragraphs.

 <style>
      body {
          font-family: Arial, sans-serif;
          margin: 0;
          padding: 0;
          background-color: #f5f5f5;
          display: flex;
          justify-content: center;
          align-items: center;
          height: 100vh;
      }
      .container {
          background-color: #fff;
          padding: 20px;
          border-radius: 10px;
          box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
          max-width: 500px;
          width: 100%;
          text-align: center;
      }
      h1 {
          margin-top: 0;
          color: #333;
      }
      input[type="text"], select, textarea {
          width: 100%;
          padding: 10px;
          margin-bottom: 10px;
          border: 1px solid #ccc;
          border-radius: 5px;
          box-sizing: border-box;
      }
      input[type="submit"] {
          background-color: #4CAF50;
          color: white;
          padding: 10px 20px;
          border: none;
          border-radius: 5px;
          cursor: pointer;
      }
      input[type="submit"]:hover {
          background-color: #45a049;
      }
      .result {
          margin-top: 20px;
      }
  </style>
</head>
<body>

Container and Header:

This part creates a container for the page as well as displays headings for the title of the app and the page.

  <div class="container">
      <h1>The Pycodes</h1>
      <h1>Google Translator</h1>

Translation Form:

We start by creating a form for the user to submit the text, then enable the user to input the said text into the form. Next, we will provide the user with a list of languages (source and target) to choose from as well as an input button to submit the form containing the text.

<form action="/translate" method="post">
          <input type="text" name="text" placeholder="Enter text" required><br>
          <select name="source_lang" required>
              <option value="" disabled selected>Select Source Language</option>
              {% for code, lang in languages.items() %}
                  <option value="{{ code }}">{{ lang }}</option>
              {% endfor %}
          </select><br>
          <select name="target_lang" required>
              <option value="" disabled selected>Select Target Language</option>
              {% for code, lang in languages.items() %}
                  <option value="{{ code }}">{{ lang }}</option>
              {% endfor %}
          </select><br>
          <input type="submit" value="Translate">
      </form>

Translation Result Section:

This part creates a container for where to display the translation result.

      <div class="result">
          {% if translated_text %}
          <p><strong>Original Text ({{ source_lang }}):</strong> {{ text }}</p>
          <p><strong>Translated Text ({{ target_lang }}):</strong> {{ translated_text }}</p>
          {% endif %}
      </div>

Closing Tags:

This one closes the opened tags: div, body, and HTML.

  </div>
</body>
</html>

Result HTML

<!DOCTYPE html>
<html>
<head>
   <title>Translation Result</title>
   <style>
       body {
           font-family: Arial, sans-serif;
           margin: 0;
           padding: 0;
           background-color: #f5f5f5;
           display: flex;
           justify-content: center;
           align-items: center;
           height: 100vh;
       }
       .container {
           background-color: #fff;
           padding: 20px;
           border-radius: 10px;
           box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
           max-width: 500px;
           width: 100%;
           text-align: center;
       }
       h1 {
           margin-top: 0;
           color: #333;
       }
       p {
           margin-bottom: 10px;
       }
   </style>
</head>
<body>
   <div class="container">
       <h1>Translation Result</h1>
       <p><strong>Original Text:</strong> {{ text }}</p>
       <p><strong>Detected Source Language:</strong> {{ source_lang }}</p>
       <p><strong>Translated Text:</strong> {{ translated_text }}</p>
   </div>
</body>
</html>

HTML Structure and Title:

Similar to the previous HTML with only the title of the web page being different.

<!DOCTYPE html>
<html>
<head>
   <title>Translation Result</title>

Cascading Style Sheets:

Similar to the previous HTML it defines the appearance of the web page: background color, font, align items, etc

   <style>
       body {
           font-family: Arial, sans-serif;
           margin: 0;
           padding: 0;
           background-color: #f5f5f5;
           display: flex;
           justify-content: center;
           align-items: center;
           height: 100vh;
       }
       .container {
           background-color: #fff;
           padding: 20px;
           border-radius: 10px;
           box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
           max-width: 500px;
           width: 100%;
           text-align: center;
       }
       h1 {
           margin-top: 0;
           color: #333;
       }
       p {
           margin-bottom: 10px;
       }
   </style>

Container and Header:

This part creates a container for the page content as well as displays a heading for the translation result.

</head>
<body>
   <div class="container">
       <h1>Translation Result</h1>

Translation Result Details:

This part displays the original text with the source language and the translated text.

       <p><strong>Original Text:</strong> {{ text }}</p>
       <p><strong>Detected Source Language:</strong> {{ source_lang }}</p>
       <p><strong>Translated Text:</strong> {{ translated_text }}</p>

Closing Tags:

This part closes the opened tags: div, body, and HTML.

   </div>
</body>
</html>

Example

Conclusion

Wrapping up, we’ve delved into Python’s capabilities for bridging language barriers, leveraging the googletrans library. This guide has equipped you with the know-how to add dynamic translation functionalities to your applications using Flask.

If any of you have questions, just leave a comment, and we’ll help you solve them. Also, I would be very happy to receive suggestions for topics that I can write about and bring to life using Flask or another framework.

Happy Coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top