How to Build a Text Simplifier with OpenAI GPT-3 and Flask

In today’s digital age, information overload is a common problem. Sometimes, we come across complex texts that are difficult to understand. To address this, we can build a Text Simplifier using the power of OpenAI GPT-3 and Flask, which will simplify complex texts and make them easier to comprehend.

In this tutorial, we will walk through the step-by-step process of building a Text Simplifier using OpenAI GPT-3 and Flask framework. By the end of this tutorial, you will be able to build a simple web application that simplifies complex texts with the help of GPT-3 and serves the simplified text through a user-friendly interface.

Prerequisites

To get started, you should have the following prerequisites:

  • Basic knowledge of Python programming language.
  • Familiarity with Flask framework.
  • OpenAI GPT-3 API key and installation of the OpenAI Python package.

If you’re new to Flask, it’s recommended to go through the Flask documentation to understand the basics before proceeding with this tutorial.

Setting up the Project

Let’s start by setting up the project’s directory structure. Open your preferred text editor or integrated development environment (IDE) and create a new directory for the project. Name it whatever you like, for example, “TextSimplifier”.

Inside the “TextSimplifier” directory, create the following files and directories:

  1. app.py: This file will contain the main Flask application code.
  2. templates/ directory: This directory will contain the HTML templates for the application.
  3. static/ directory: This directory will contain any static files required for the application (e.g., CSS stylesheets).

Your project directory structure should look like this:

TextSimplifier/
โ”œโ”€โ”€ app.py
โ”œโ”€โ”€ templates/
โ””โ”€โ”€ static/

Installing Required Dependencies

Next, let’s install the required dependencies for our project. Open a terminal or command prompt, navigate to your project directory (TextSimplifier), and run the following command to create a virtual environment:

python3 -m venv venv

After creating the virtual environment, activate it by running the following command:

  • On macOS/Linux:
source venv/bin/activate
  • On Windows (PowerShell):
.venvScriptsActivate.ps1

Now that the virtual environment is activated, let’s proceed with installing the necessary dependencies. We’ll use pip to install Flask and OpenAI packages. Run the following command in the terminal:

pip install flask openai

With the dependencies installed, we can proceed to develop our Text Simplifier application.

Creating the Flask Application

Open the app.py file in your chosen text editor or IDE and let’s start building our Flask application.

First, let’s import the required modules. Add the following code to the top of the app.py file:

from flask import Flask, render_template, request
import openai

Next, let’s initialize the Flask application and set up the OpenAI GPT-3 API. Add the following code:

app = Flask(__name__)

# Set up OpenAI GPT-3 API
openai.api_key = "YOUR_API_KEY"

Make sure to replace "YOUR_API_KEY" with your actual GPT-3 API key.

Now, let’s create the routes for the application.

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

Here, @app.route("/") is a decorator that maps the URL path “/” to the index function. The index function returns the rendered index.html template.

We’ll create the index.html template shortly. It will contain a simple form where the user can input the complex text to be simplified.

Next, let’s create the route to handle form submissions and simplify the text using GPT-3. Add the following code:

@app.route("/simplify", methods=["POST"])
def simplify():
    # Retrieve the complex text from the form input
    complex_text = request.form["complex"]

    # Call GPT-3 to simplify the text
    simplified_text = gpt3_simplify(complex_text)

    return render_template("result.html", complex=complex_text, simplified=simplified_text)

In this route, we handle POST requests made to the “/simplify” URL path. We retrieve the complex text from the form input using request.form["complex"]. Then, we call the gpt3_simplify function to simplify the text using GPT-3.

Finally, we render the result.html template and pass the complex and simplified texts as variables to be displayed in the template.

The only thing missing now is the gpt3_simplify function, which we’ll implement next.

Simplifying Text with GPT-3

Before we define the gpt3_simplify function, let’s briefly discuss how we can simplify text using GPT-3.

OpenAI GPT-3 is a powerful language model that can generate human-like text based on the provided prompt. We can leverage this capability to generate simpler text based on complex input.

To simplify text using GPT-3, we need to construct a prompt that instructs the model to make the text simpler. For example, we can use a prompt like “Simplify the following text:” and append the complex text as the input.

Once we receive the simplified text from GPT-3, we need to extract it from the generated response. This can be done by processing the GPT-3 response using the OpenAI Python package functions.

Now, let’s define the gpt3_simplify function in the app.py file. Add the following code:

def gpt3_simplify(complex_text):
    # Construct the prompt for GPT-3
    prompt = f"Simplify the following text:n{complex_text}"

    # Call GPT-3 to generate the simplified text
    response = openai.Completion.create(
        engine="text-davinci-003",
        prompt=prompt,
        max_tokens=100,
        temperature=0.5,
        n=1,
        stop=None,
        temperature=0.7
    )

    # Extract the simplified text from GPT-3 response
    simplified_text = response.choices[0].text.strip()

    return simplified_text

In this function, we first construct the prompt by appending the complex text to the prompt message. Then, we call the openai.Completion.create function to generate the simplified text.

The engine parameter specifies the GPT-3 engine to use. You can experiment with different engines to get different results. We use text-davinci-003 in this example, which is a popular choice for text generation tasks.

The max_tokens parameter sets the maximum number of tokens to generate. In this case, we limit it to 100 tokens for simplicity.

The temperature parameter controls the randomness of the generated text. Higher values like 0.7 make the text more diverse, while lower values like 0.3 make it more focused and deterministic. You can experiment with different temperature values to achieve the desired output.

Finally, we extract the simplified text from the GPT-3 API response and return it.

With the gpt3_simplify function defined, our Flask application is ready to serve the simplified text.

Creating the HTML Templates

Now, let’s create the HTML templates for our application. For simplicity, we’ll create two templates: index.html and result.html.

Create the index.html file inside the templates/ directory and add the following HTML code:

<!DOCTYPE html>
<html>
<head>
    <title>Text Simplifier</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>Text Simplifier</h1>
    <form action="/simplify" method="post">
        <textarea name="complex" rows="10" cols="50" required></textarea><br>
        <input type="submit" value="Simplify">
    </form>
</body>
</html>

Here, we have a simple form that contains a textarea where the user can input the complex text. The form is submitted to the “/simplify” URL path when the user clicks the “Simplify” button.

Notice the {{ url_for('static', filename='style.css') }} in the <link> tag. This is a Flask template variable that generates the correct URL path to the static CSS stylesheet. We’ll create the style.css file shortly.

Next, create the result.html file inside the templates/ directory and add the following HTML code:

<!DOCTYPE html>
<html>
<head>
    <title>Text Simplifier - Result</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>Text Simplifier - Result</h1>
    <h2>Complex Text:</h2>
    <p>{{ complex }}</p>
    <h2>Simplified Text:</h2>
    <p>{{ simplified }}</p>
    <a href="/">Back</a>
</body>
</html>

In this template, we show the complex and simplified texts as paragraphs. We also add a “Back” link that redirects the user back to the index page.

Now, create a style.css file inside the static/ directory and add the following CSS code:

body {
    font-family: Arial, sans-serif;
    margin: 20px;
    padding: 0;
}
h1, h2, p {
    margin: 0;
    padding: 0;
}
textarea {
    width: 100%;
}

This CSS code sets some basic styling for our application. Feel free to customize it further if desired.

Running the Application

With everything set up, it’s time to run our Text Simplifier application!

In the terminal or command prompt, make sure you are in the project’s root directory (TextSimplifier) and run the following command to start the Flask development server:

flask run

If everything is set up correctly, you should see output similar to the following:

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Open your web browser and navigate to `http://localhost:5000` to access the Text Simplifier application.

Conclusion

Congratulations! You have successfully built a Text Simplifier using OpenAI GPT-3 and Flask. You’ve learned how to set up a Flask application, integrate OpenAI GPT-3 API, and simplify complex texts using GPT-3.

Remember to keep your GPT-3 API key secure and never commit it to public repositories.

Feel free to enhance the application further by adding more features such as error handling, input validation, or applying additional post-processing to the simplified text.

You can also explore integrating other technologies like natural language processing libraries or machine learning models to enhance the simplification process.

Happy simplifying!

Related Post