Filter Image Uploads According to their NSFW Score
Tags: webdev, tutorial, python, php
Published: 2020-05-31 22:44:38

---
title: Filter Image Uploads According to their NSFW Score
published: true
description: Learn how to automatically filter users image uploads according to their NSFW score via the PixLab NSFW API endpoint.
tags: webdev, tutorial, python, php
cover_image: https://thepracticaldev.s3.amazonaws.com/i/tt8datskl5qsksdrqpgd.jpg
---

When developing and later administrating a web or mobile application that deals with lot of image uploads, shares, likes and so forth, you would want to setup a **smart automated mechanism that moderate** your users image, GIF or video uploads on the fly and act accordingly when **NSFW content is being detected** such as rejecting, flagging or even censoring (i.e. apply a blur filter to) the target picture or video frame being suspected.

Since images and user-generated content dominate the Internet today, filtering NSFW contents becomes an essential component of Web and mobile applications. NSFW is the acronym for ***not safe for work*** and refer to images or GIF frames that contain adult content, violence or gory details.

In the scale of the modern web, it is impractical to rely on a human operator to moderate each image upload one after one. Instead, **Computer Vision**, a field of Artificial Intelligence is used for such a task. Computers are now able to automatically classify NSFW image content with greater precision & speed.

In this post, you will learn how to make use of the PixLab API to detect and filter unwanted contents (GIF included) and make decisions based on the *score number* from PixLab to blur the image in question or delete it.

## Table Of Contents
* [The PixLab API](#chapter-1)
* [The NSFW Endpoint](#chapter-2)
* [Real World Code Sample](#chapter-3)
* [PHP/Python Gist](#chapter-5)
* [Conclusion](#chapter-4)

###The PixLab API <a name="chapter-1"></a>
![PixLab Logo](https://thepracticaldev.s3.amazonaws.com/i/trftcoh1aq5ta4zn9a6o.png)

[PixLab](https://pixlab.io) is a Machine Learning SaaS platform which offer Computer Vision and Media Processing APIs either via a straightforward **HTTP RESTful API** or offline SDK via the [SOD Embedded CV library](https://sod.pixlab.io). PixLab HTTP API feature set includes but not not limited to:
<ul>
<li>Over 130 Machine Vision &amp; Media Processing <a href="https://pixlab.io/cmdls">API endpoints</a>.</li>
<li>State-of-the-art document scan algorithms such as Passports, ID cards via the /<a href="https://pixlab.io/cmd?id=docscan">docscan</a> API endpoint, face detection (/<a href="https://pixlab.io/cmd?id=facedetect">facedetect</a>), facial landmarks extraction (/<a href="https://pixlab.io/cmd?id=facelandmarks">facelandmarks</a>), facial recognition (/<a href="https://pixlab.io/cmd?id=facecompare">facecompare</a>), NSFW content analysis (/<a href="https://pixlab.io/cmd?id=nsfw">nsfw</a>) and <a href="https://pixlab.io/cmdls">many more</a>.</li>
<li>1TB of media storage served from a highly available CDN over SSL.</li>
<li>On the fly image compression, encryption and tagging.</li>
<li>Proxy for AWS S3 and other cloud storage providers.</li>
</ul>

###Invoking the NSFW Endpoint <a name="chapter-2"></a>

According to the <a href="https://pixlab.io/cmdls">PixLab documentation</a>. The purpose of <a href="https://pixlab.io/cmd?id=nsfw">NSFW</a> is to detect not suitable for work (i.e. nudity & adult) content in a given image or video frame. **NSFW** is of particular interest, if mixed with some media processing API endpoints like <a href="https://pixlab.io/cmd?id=blur">blur</a>, <a href="https://pixlab.io/cmd?id=encrypt">encrypt</a> or <a href="https://pixlab.io/cmd?id=mogrify">mogrify</a> to censor images on the fly according to their **nsfw score**. This can help the developer automate things such as filtering user's upload.

###HTTP Methods

The <a href="https://pixlab.io/cmd?id=nsfw">NSFW</a> endpoint support both **GET** and **POST** HTTP methods which mean that you can send either a direct link (public URL) to the target image to scan via **GET** or upload the image directly from your HTML form or Web app for example to the NSFW endpoint via **POST**. POST on the other side is more flexible and support two content types: ***multipart/form-data*** and ***application/json***.

###API Response

The NSFW API endpoint always return a **JSON object** (i.e. *application/json*) for each HTTP request whether successful or not. The following are the JSON fields returned in response body:

* **Status**
* **Score**
* **Error**

The field of interest here is the **score** value. **The more this value approaches 1, the more your picture is highly nsfw**. In which case, you have to act accordingly such as rejecting the picture or better, apply a <a href="https://pixlab.io/cmd?id=blur" target="_blank">blur filter</a> (see example below) to the picture in question.

###Real World Code Sample<a name="chapter-3"></a>

Given a freshly uploaded image, perform **nudity & adult content detection** at first and if the **nsfw score is high enough**, apply a blur filter on the target picture. A typical (highly nsfw) blurred image should look like the following after processing:

![Censored NSFW Picture](https://thepracticaldev.s3.amazonaws.com/i/tt8datskl5qsksdrqpgd.jpg)

Such blurred image was obtained via the following [Python script](https://github.com/symisc/pixlab/tree/master/python):

```python
import requests
import json

# Target Image: Change to any link (Possibly adult) you want or switch to POST if you want to upload your image directly, refer to the sample set for more info.
img = 'https://i.redd.it/oetdn9wc13by.jpg' 
# Your PixLab API key that you can obtain from https://pixlab.io/dashboard
key = 'PIXLAB_API_KEY'

# Censure an image based on its NSFW score
req = requests.get('https://api.pixlab.io/nsfw',params={'img':img,'key':key})
reply = req.json()
if reply['status'] != 200:
	print (reply['error'])
elif reply['score'] < 0.5 :
    print ("No adult content were detected on this picture")
else:
	# Highly NSFW picture
	print ("Censuring NSFW picture...")
	# Call blur with the highest possible radius and sigma
	req = requests.get('https://api.pixlab.io/blur',params={'img':img,'key':key,'rad':50,'sig':30})
	reply = req.json()
	if reply['status'] != 200:
		print (reply['error'])
	else:
		print ("Blurred Picture URL: "+ reply['link'])
```

* A PHP code sample is also available [here](https://gist.github.com/symisc/6522ea8f5c577bc1136029a679ab04c3).

The code above is self-explanatory and regardless of the programming language, **the logic is always same**. We made a simple HTTP GET request with the input image URL as a sole parameter. Most [PixLab endpoints](https://pixlan.io/cmdls) support multiple HTTP methods so you can easily switch to POST based requests if you want to upload your images & videos directly from your mobile or web app for anlaysis. Back to our sample, only two API endpoints are needed for our moderation task:

1. First, <a href="https://pixlab.io/cmd?id=nsfw">NSFW</a> is the analysis endpoint that must be called first. It does perform nudity & adult content detection and return a **score value between 0..1**. The more this value approaches 1, the more your picture/frame is highly nsfw.
2. The <a href="https://pixlab.io/cmd?id=nsfw">Blur</a> endpoint is called later **only if the nsfw score value returned earlier is greater than certain threshold**. In our case, it is set to 0.5. The blur endpoint return either a direct link (URL) to the blurred image which is stored on the PixLab storage cluster or on your own AWS S3 bucket if you connect your bucket (i.e. Access/Secret S3 key) from the <a href="https://pixlab.io/dashboard">PixLab dashboard</a>. This feature should give full control over your processed (i.e. censored) images.

###PHP/Python Gist <a name="chapter-5"></a>

{% gist https://gist.github.com/symisc/6522ea8f5c577bc1136029a679ab04c3 %}

###Conclusion <a name="chapter-4"></a>
Surprisingly, automatically filtering unwanted contents is straightforward for the average web developer or site administrator who may lack technical machine learning skills thanks to open computer vision technologies such the one provided by PixLab. Find out more code samples on https://github.com/symisc/pixlab and https://github.com/symisc/sod if your are C/C++ developer.