top of page

Building a Simple French Translator Web App Using Flask and OpenAI

Language translation is a powerful tool in breaking down communication barriers. With advancements in AI, it has become easier to create applications that can translate text between languages. In this blog, we'll walk through the creation of a simple web-based French translator using Flask and OpenAI's GPT model. The provided code handles user input, sends the text to OpenAI's API for translation, and returns the translated text in French.


Introduction

The goal of this project is to develop a web application that translates English text into French. The application uses Flask, a lightweight web framework, to handle web requests and serve pages, while the translation is performed using OpenAI's GPT model. The application also includes a simple web interface for user interaction.


What You Will Learn

By the end of this tutorial, you will learn:

  • How to set up a Flask application.

  • How to integrate OpenAI's GPT model into a Flask app for translation tasks.

  • How to create a simple web interface using HTML and CSS.

  • How to handle GET and POST requests in Flask.


Prerequisites

Before starting, ensure you have the following installed:

  • Python

  • Flask (pip install flask)

  • OpenAI's Python client (pip install openai)


Understanding the Provided Code

Let's go through the provided code step by step.


1. Importing Required Libraries and Setting Up Flask

from flask import Flask, session, request, jsonify, render_template
import openai
import os
from openapi import OPEN_API_KEY
  • Flask: The Flask library is imported to create the web application. It provides essential tools for handling requests, sessions, and rendering HTML templates.

  • OpenAI: This is used to interact with OpenAI's API, which will perform the translation.

  • OS and API Key: The os library is used for environment-related operations, and the OpenAI API key is imported from a separate file (openapi.py).


2. Configuring the Flask App

openai.api_key = OPEN_API_KEY

app = Flask(__name__)
app.config.update(ENV='development')
app.config.update(SECRET_KEY='878as7d8f7997dfaewrwv8asdf8)(dS&A&*d78(*&ASD08A')

SESSION_KEY = "json"
  • API Key: The API key is set to authenticate requests to OpenAI's servers.

  • Flask Configuration: The Flask app is configured with environment settings and a secret key used for session management.


3. Defining the Translation Function

def __default_message(message: str):
    prompt = f"Translate the following English text to French: '{message}'"

    result = openai.Completion.create(
        model="text-davinci-003",
        prompt=prompt,
        max_tokens=3000,
        temperature=1.2
    )
    print(result)
    return {"translation": result["choices"][0]["text"]}
  • Prompt Preparation: The input message is formatted into a prompt that asks the GPT model to translate the text into French.

  • API Call: The openai.Completion.create method is used to send the prompt to OpenAI’s API. The text-davinci-003 model is specified for the task, with parameters like max_tokens and temperature controlling the response's length and creativity.

  • Return Value: The function returns the translation wrapped in a dictionary.


4. Setting Up Flask Routes

Home Route

@app.route('/')
def home():
   return render_template("index.html")
  • Home Page: The home route renders the index.html template, which is the main page of the application where users can input text for translation.


Translation Route (GET Request)

@app.route("/translate", methods=["GET"])
def get():
    text = request.args.get("text")
    response = jsonify(__default_message(text), 200)
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response
  • GET Request Handling: This route handles GET requests, extracting the text to be translated from the query parameters. It then calls the __default_message function to perform the translation and returns the result as a JSON response.


Translation Route (POST Request)

@app.route("/post", methods=["POST"])
def post():
    post = request.get_json()
    print(post)
    
    if post is not None:
        session[SESSION_KEY] = post
        return jsonify(__default_message(post["text"]), 201)
    else:
        return jsonify(__default_message(message="wrong payload"), 400)
  • POST Request Handling: This route handles POST requests, where the text to be translated is sent in the request body as JSON. The function checks if the request contains data, processes the translation, and returns the result. If the request is empty or malformed, it returns an error message.


5. Running the Flask Application

app.run(host="127.0.0.1", port=5001, debug=True)
  • Running the App: The application is set to run on localhost at port 5001, with debug=True to allow for easy debugging during development.


The User Interface

The application’s user interface is defined in the index.html file. This file contains HTML, CSS, and JavaScript to create a simple and responsive interface for the translation app.


HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NVC Translator</title>
    <link href="{{ url_for('static', filename='style.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
    <nav class="navigation container">
        <div class="nav-brand">French Translator </div>
        <ul class="list-non-bullet nav-pills">
            <li class="list-item-inline">
                <a class="link link-active" href="/">home</a>
            </li>
        </ul>
    </nav>

    <div class="container container-center">
        <header class="hero">
            <h1 class="hero-heading">French Translator</h1>
        </header>

        <div class="justify">
            <textarea id="input-translate" placeholder="Enter text you want to translate..."></textarea>
        </div>

        <div class="spinner-container">
            <button class="link link-primary" id="btn-translate">Translate to French</button>
            <div id="loading" class="spinner" style="display: none;"></div>
        </div>

        <div id="output-translate">Output of the translation</div>
    </div>
    <script src="{{ url_for('static', filename='app.js') }}"></script>
</body>
</html>
  • Navigation Bar: The navigation bar contains a simple brand name and a link to the home page.

  • Text Area and Button: A textarea allows users to input text for translation, and a button triggers the translation process.

  • Translation Output: The result of the translation is displayed in a div with the ID output-translate.


Running the Application

To run this application:

  1. Save the app.py and index.html files in their respective directories.

  2. Ensure you have Flask and OpenAI's Python client installed.

  3. Run the Flask app using python app.py.

  4. Open your web browser and navigate to http://127.0.0.1:5001/.


Complete Code

from flask import Flask, session, request, jsonify, render_template
import openai
import os
from openapi import OPEN_API_KEY

openai.api_key = OPEN_API_KEY

app = Flask(__name__)
app.config.update(ENV='development')
app.config.update(SECRET_KEY='878as7d8f7997dfaewrwv8asdf8)(dS&A&*d78(*&ASD08A')

SESSION_KEY = "json"

def __default_message(message:str):
    
    prompt = f"Translate the following English text to French: '{message}'"

    result = openai.Completion.create(
        model="text-davinci-003",
        prompt=prompt,
        max_tokens=3000,
        temperature=1.2
    )
    print(result)
    return {"translation": result["choices"][0]["text"]}


@app.route('/')
def home():
   return render_template("index.html")

@app.route("/translate", methods=["GET"])
def get():
    # get = session.get(SESSION_KEY)
    text = request.args.get("text")
    response = jsonify(__default_message(text), 200)
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response # For some reason the response comes back with leading \n's; trimming in js for now


@app.route("/post", methods=["POST"])
def post():
    post = request.get_json()
    print(post)
    
    if post is not None:
        session[SESSION_KEY] = post
        return jsonify(__default_message(post["text"]), 201)
    else:
        return jsonify(__default_message(message="wrong payload"), 400)

app.run(host="127.0.0.1", port=5001, debug=True) # uncomment to run locally #runningLocally #ref
<!DOCTYPE html>
<html lang="en">

<head>
    <!-- Google tag (gtag.js) -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-MD6L3WYG0S"></script>
    <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config', 'G-MD6L3WYG0S');
    </script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NVC Translator</title>
    <link rel="apple-touch-icon" sizes="180x180" href="../static/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="../static/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="../static/favicon-16x16.png">
    <link rel="manifest" href="../static/site.webmanifest">
    <meta name="msapplication-TileColor" content="#da532c">
    <meta name="theme-color" content="#ffffff">
    <link href="{{ url_for('static', filename='style.css') }}" rel="stylesheet" type="text/css" />
    <script src="https://kit.fontawesome.com/1a48924413.js" crossorigin="anonymous"></script>
</head>

<body>
    <!-- nav -->

    <nav class="navigation container">
        <div class="nav-brand">French Translator </div>
        <ul class="list-non-bullet nav-pills">
            <li class="list-item-inline">
                <a class="link link-active"  href="/">home</a>
            </li>
        </ul>
    </nav>

    <!-- translator -->

    <div class="container container-center">
        <header class="hero">
            <!-- <img class="hero-img" style="padding:0 0px 0 0px;width:230px"  src="{{ url_for('static', filename='giraffe_cropped.png') }}" /> -->
            <h1 class="hero-heading">French Translator</h1>
        </header>

        <div class="justify">
            <textarea id="input-translate" placeholder="Enter text you want to translate, e.g. “You never text me and I feel abandoned.”"></textarea>
            <!-- <textarea id="input-translate" placeholder="Enter a text you've received, or a text you're thinking to send, that you want to translate, e.g. “You never call me and I feel abandoned”"></textarea> -->
        </div>

        <div class="spinner-container">
            <button class="link link-primary" id="btn-translate">Translate to French</button>
            <div id="loading" class="spinner" style="display: none;"></div>
        </div>

        <div id="output-translate">Output of the translation</div>
    </div>
    <script src="{{ url_for('static', filename='app.js') }}"></script>
</body>

</html>

This blog has walked you through building a simple French translator web application using Flask and OpenAI's GPT model. The app accepts English text from the user, sends it to OpenAI’s API for translation, and returns the French translation. This project demonstrates the power of combining Flask with AI services to create useful web applications.


Project Demo Video



You can expand this project by adding more features, such as support for multiple languages, improved error handling, or deploying the app on a cloud platform for broader accessibility.


If you require any assistance with this project or Machine Learning projects, please do not hesitate to contact us. We have a team of experienced developers who specialize in Machine Learning and can provide you with the necessary support and expertise to ensure the success of your project. You can reach us through our website or by contacting us directly via email or phone.


Comments


bottom of page