Image upload and moderation with Python and Flask

Almost all applications contain images. Image moderation has become a necessity. We will see in this article how to moderate your images automatically.

We are going to create a small application that lets users upload images and check if those images contain inappropriate content.

We need to install the dependencies. Two dependencies will be needed to create our application.

  • Flask: Creates a web server
  • Sightengine: The SDK that will allow us to automatically moderate our images
pip install sightengine flask

1# Create the web server with Flask

Let’s start out by creating the server with an app.py file:

In a second step we will create a folder called templates with an index.html file inside.

You can now run the server with:

export FLASK_APP=app.py
flask run

2# Upload your images

The first step is to create an upload folder. This folder will be used to store our images.

The second step is to modify our server. The images will be automatically sent to the upload folder we created before.

We will also modify our index.html file to add a form for file upload.

3# Moderate the images with Sightengine

Sightengine is an API that lets you to moderate images. There are 8 models currently available.

  • Nudity detection (i.e. detect adult or suggestive content)
  • Weapons/Alcohol/Drugs detection
  • Face/People detection (i.e. detect if the image contains a person or several people or nobody, along with the positions of those faces)
  • Face Attributes detection (get the age group and gender, determine if a face is covered with sunglasses…)
  • Celebrity detection
  • Image type detection (i.e. detect if the image is a natural photograph or an illustration)
  • Image Properties (i.e. determine the quality of an image along with its main colors)
  • Scammer detection (detect if an image is likely to have been submitted by a romance scammer)

You must first register on Sightengine’s website, it’s totally free. Just click on the get started button and create an account.

Once logged in, click on the get started page. Sightengine works with two keys, we will need these keys to use the SDK in our application. Be careful, do not share them, they are secret keys.

For the purpose of this tutorial, we will activate the nudity, scammer, celebrity, minor and inappropriate content (drugs, alcohol, weapons) models.

You might want to add or remove some of those models depending on your specific needs.

The API is simple to use. Here is an example output:

We will modify our server to add the Sightengine SDK. If the moderation succeeded, the image will we uploaded otherwise an error message will be displayed.

We will then add the data returned by the server into our index.html file.

# Final thoughts

I hope this was helpful. If you want to know more about Sightengine you can try their demo. The complete code is accessible here. Feel free to share and recommend if useful :)