DEV Community

Cover image for NSFW API Guide: How to Censor Sexual Content in Videos
Tarana Murtuzova for API4AI

Posted on

NSFW API Guide: How to Censor Sexual Content in Videos

Introduction

In today's digital world, content moderation is crucial for maintaining a safe and welcoming online environment. With the vast amount of video content being uploaded daily, the challenge of managing NSFW (Not Safe For Work) content has become more urgent than ever. Whether for social media platforms, educational tools, or content creation, ensuring explicit content is appropriately moderated is essential for protecting users and maintaining brand integrity.

This blog post will guide you through the process of blurring sexual content in videos using the NSFW API from API4AI, conveniently available on Rapid API Hub. By leveraging this powerful tool, you can efficiently detect and blur NSFW content, making your videos suitable for all audiences. Whether you're a content creator looking to uphold a professional image, an educator needing to provide safe learning materials, or a platform owner striving to comply with content guidelines, this tutorial will give you the necessary steps to implement an effective content moderation solution.

The benefits of using the NSFW API are numerous. It offers high accuracy and speed, making it ideal for real-time applications. Additionally, its ease of integration allows you to quickly implement it into your existing workflows without requiring extensive technical expertise. By the end of this post, you will understand how to use this API to blur NSFW content in your videos, helping you create a safer and more user-friendly experience for your audience.

Understanding NSFW Content

Definition

NSFW (Not Safe For Work) content includes any material that is unsuitable for viewing in public or professional settings. This usually involves sexually explicit images or videos but can also cover violent, profane, or otherwise offensive material. The need to manage NSFW content arises from the diverse audience accessing digital platforms; what may be acceptable in one context can be highly inappropriate or offensive in another. Identifying and moderating such content is essential for maintaining a respectful and professional environment, safeguarding the reputation of digital platforms, and complying with legal and regulatory standards.

Impact of NSFW Content

Unmoderated NSFW content can have significant negative consequences for various audiences. For individuals, especially younger viewers or those who may find explicit content distressing, encountering NSFW material can cause discomfort, harm, or trauma. For content creators and platform owners, the presence of unmoderated NSFW content can damage reputations, erode user trust, and lead to potential legal issues. Educational institutions and professional organizations can face severe backlash if such content appears in materials meant for public or academic use. Overall, the presence of NSFW content in inappropriate contexts can significantly undermine the credibility and safety of digital environments.

Content Moderation

Content moderation entails the processes and technologies used to detect, review, and manage NSFW content to prevent its inappropriate distribution. Several methods and tools are available for content moderation, each with its own advantages and drawbacks:

  • Manual Review: Involves human moderators examining content. Although accurate, this method is time-consuming, costly, and not scalable for large volumes of content.
  • Automated Filters: Utilize algorithms to identify and filter NSFW content. These can be efficient but may lack the subtlety and precision of human judgment.
  • AI and Machine Learning: Use advanced AI models to recognize NSFW content with high accuracy. These systems can process large amounts of data swiftly and improve over time with continued training.

Among these methods, AI and machine learning have emerged as powerful tools for content moderation. The NSFW API from API4AI exemplifies this by offering an efficient and reliable tool for detecting and managing NSFW content. With its high accuracy, speed, and ease of integration, the NSFW API provides a robust solution for ensuring explicit content is properly moderated. This makes it an essential tool for content creators, educators, and platform managers. This API, available through the Rapid API Hub, will be the focus of our guide, demonstrating how to effectively use it to blur NSFW content in videos.

Introduction to the NSFW API

What is the NSFW API?

The NSFW API, developed by API4AI, is a robust tool designed to detect and manage NSFW (Not Safe For Work) content in digital media. This API uses advanced machine learning algorithms to identify sexually explicit material within images and videos, offering an automated solution for content moderation. By integrating the NSFW API into your workflow, you can efficiently ensure that explicit content is properly flagged or blurred, enhancing the safety and suitability of your platform for all users.

Key Features

The NSFW API from API4AI is equipped with a range of features that make it an excellent choice for content moderation:

  • Detection of NSFW Content: The primary function of the NSFW API is to accurately identify explicit material in videos and images, including nudity, sexual acts, and other adult content.
  • High Accuracy: The API employs state-of-the-art machine learning models trained on extensive datasets, ensuring precise detection of NSFW content.
  • Speed: The NSFW API processes content swiftly, making it ideal for real-time applications where rapid moderation is essential.
  • Ease of Use: Designed with developers in mind, the API is easy to integrate into existing systems, supported by comprehensive documentation and assistance.
  • Scalability: Capable of handling large volumes of content, the API is well-suited for platforms with significant user-generated content.

Advantages

Utilizing the NSFW API from API4AI presents several benefits over traditional content moderation methods:

  • Efficiency: Automated detection minimizes the need for manual review, saving both time and resources. This is especially advantageous for platforms with a high volume of user-generated content.
  • Consistency: Unlike human moderators, the API delivers consistent results, eliminating subjective judgments and potential errors.
  • Real-Time Moderation: The rapid processing speed of the NSFW API enables real-time moderation, ensuring that inappropriate content is flagged or blurred almost immediately.
  • Cost-Effective: By reducing the dependency on human moderators, the NSFW API can lower the operational costs associated with content moderation.
  • Continuous Improvement: The machine learning models behind the NSFW API continually improve as they process more data, resulting in increased accuracy and efficiency over time.

Incorporating the NSFW API into your content moderation strategy provides a robust, scalable, and efficient solution for managing explicit content, ensuring a safer and more user-friendly experience for your audience. In the following sections, we will guide you through setting up and using this powerful tool to blur NSFW content in videos.

Setting Up the NSFW API

Prerequisites

Before you can begin using the NSFW API to blur explicit content in videos, make sure you have the following prerequisites:

  • API Key: Obtain an API key to access the NSFW API by subscribing to it on the Rapid API Hub.
  • Python: Ensure that Python is installed on your system. You can download it from the official Python website.
  • Python Libraries: Install the necessary libraries such as aiohttp for making API calls and opencv-python for video processing. These can be installed using pip:
pip install opencv-python aiohttp
Enter fullscreen mode Exit fullscreen mode

Subscribing to the API on Rapid API Hub

To use the NSFW API, you need to subscribe to it on Rapid API Hub. Follow these steps:

Create an Account on Rapid API Hub:

  • Visit the Rapid API Hub website.
  • Click on the "Sign Up" button to create an account. If you already have an account, click "Log In."
  • Follow the instructions to complete the sign-up or log-in process.

Locate the NSFW API:

  • Once logged in, use the search bar to look for "NSFW" or follow this link directly.
  • Select the NSFW API from the search results to access its page.

Subscribe to the API:

  • On the NSFW API page, view the available subscription plans.
  • Select a pricing plan that meets your needs (a free tier may be available for testing purposes).
  • Complete the subscription process as instructed.

Retrieve Your API Key:

  • After subscribing, go to your Dashboard.
  • On the left side of the screen, look for an entry like “default-application_xxxxxx.”
  • Navigate to the Authorization section and copy your Application Key.

Image description

Verifying the API

After subscribing to the NSFW API and obtaining your API key, it's important to ensure that the API is functioning correctly. The easiest way to verify this is by running the following command (replace YOUR_API_KEY with your actual API key and image.jpg with the path to any image on your workstation):

curl -X "POST" \
  "https://nsfw3.p.rapidapi.com/v1/results" \
  -H 'X-RapidAPI-Key: YOU_API_KEY' -F "image=@image.jpg"
Enter fullscreen mode Exit fullscreen mode

If you receive a successful response, it indicates that the API is functioning properly. For more information, refer to the API documentation.

By completing these steps, you can ensure your environment is correctly set up and that the NSFW API is ready for use. In the next section, we will show you how to create a Python script to blur NSFW content in a video file using this API.

Blurring Explicit Content in Videos with Python

Overview

In this section, we will guide you through creating a Python script to blur NSFW content in a video file using the NSFW API from API4AI. The script will carry out the following tasks: parse command-line arguments, split the video into frames, check each frame for NSFW content, and blur the frames containing such material. Finally, it will reassemble the frames into a processed video.

Parsing Command-Line Arguments

To make our script flexible and user-friendly, we'll utilize the argparse module to handle command-line arguments. This will allow us to specify the input video file and the output file for the processed video.

def parse_args():
    """Parse command line arguments."""
    parser = argparse.ArgumentParser()
    parser.add_argument('--api-key', help='Rapid API key.', required=True)  # Get your token at https://rapidapi.com/api4ai-api4ai-default/api/nsfw3/pricing
    parser.add_argument('--input', type=Path,
                        help='Path to input video.')
    parser.add_argument('--output', type=Path,
                        help='Path to output video.')
    return parser.parse_args()
Enter fullscreen mode Exit fullscreen mode

Breaking the Video into Frames

Next, we need to divide the video into individual frames for processing. The split_video_by_frames function will return a generator that produces each frame from the video.

def split_video_by_frames(cap: cv2.VideoCapture):
    """Split video by frames using OpenCV."""
    while cap.isOpened():
        success, image = cap.read()
        if not success:
            break
        yield image
Enter fullscreen mode Exit fullscreen mode

Verifying NSFW Content in Frames

We'll develop a function to evaluate each frame for NSFW content using the NSFW API. This function will send each frame to the API and return a boolean indicating if the frame contains NSFW material. The is_frame_nsfw function will be asynchronous to expedite video processing. It returns probabilities indicating the likelihood that the content is not safe for work, for example: {"nsfw": 0.6, "sfw": 0.4}.

async def is_frame_nsfw(img: np.ndarray, api_key: str) -> dict:
    url = f'{API_URL}'
    async with aiohttp.ClientSession() as s:
        async with s.post(url,
                          data={'image': cv2.imencode('.jpg', img)[1].tobytes()},
                          headers={'X-RapidAPI-Key': api_key}) as api_res:
            try:
                api_res_json = await api_res.json()
            except aiohttp.client.ContentTypeError:
                raise RuntimeError(await api_res.text())

    # Handle processing failure.
    if (api_res.status != 200 or
            api_res_json['results'][0]['status']['code'] == 'failure'):
        raise RuntimeError(await api_res.text())

    probs = api_res_json['results'][0]['entities'][0]['classes']
    return probs
Enter fullscreen mode Exit fullscreen mode

Main Function

We'll integrate the functions mentioned above into the main function to process the video: breaking it into frames, checking each frame for NSFW content, blurring the NSFW frames, and then reassembling the video.

async def main():
    args = parse_args()

    # Open a video
    cap = cv2.VideoCapture(str(args.input))
    fps = cap.get(cv2.CAP_PROP_FPS)
    size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
            int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    frames = list(split_video_by_frames(cap))

    print("Sending video to NSFW API.")
    # asyncio is used to speed up working with NSFW API by sending HTTP requests asynchronously.
    probs_frames = await asyncio.gather(
        *[is_frame_nsfw(frame, args.api_key)
          for frame in frames],
        return_exceptions=True
    )

    print("Blurring the video.")
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(str(args.output), fourcc, fps, size)
    for i, (prob, frame) in enumerate(zip(probs_frames, frames)):
        # If exception was thrown in is_frame_nsfw
        if issubclass(type(prob), Exception):
            print(f'Frame {i} was not handled. Reason: {prob}')
            out.write(frame)
            continue

        if prob['nsfw'] > THRESHOLD:
            out.write(cv2.blur(frame, (250, 250)))
        else:
            out.write(frame)

    out.release()
    cap.release()
    print(f'New video created: {args.output}.')

if __name__ == '__main__':
    asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

Full Python Script

Here is the complete Python script that brings together all the functions described above:

"""
Blur NSFW content in a video using NSFW API.

Run script:
`python3 main.py --api-key <RAPID_API_KEY> --input <PATH_TO_ORIGINAL_VIDEO> --output <PATH_TO_OUTPUT_VIDEO>`
"""

import argparse
import asyncio
from pathlib import Path

import aiohttp
import cv2
import numpy as np

API_URL = 'https://nsfw3.p.rapidapi.com/v1/results'
THRESHOLD = 0.5


def parse_args():
    """Parse command-line arguments."""
    parser = argparse.ArgumentParser()
    parser.add_argument('--api-key', help='Rapid API key.', required=True)  # Get your token at https://rapidapi.com/api4ai-api4ai-default/api/nsfw3/pricing
    parser.add_argument('--input', type=Path,
                        help='Path to input video.')
    parser.add_argument('--output', type=Path,
                        help='Path to output video.')
    return parser.parse_args()


async def is_frame_nsfw(img: np.ndarray, api_key: str) -> dict:
    """
    Get probabilities of NSFW content using NSFW API.

    Function is asynchronous in order to process video faster.

    Returns
    -------
    Returns probabilities that content is NSFW.
    Example: {"nsfw": 0.6, "sfw": 0.4}
    """
    url = f'{API_URL}'
    async with aiohttp.ClientSession() as s:
        async with s.post(url,
                          data={'image': cv2.imencode('.jpg', img)[1].tobytes()},
                          headers={'X-RapidAPI-Key': api_key}) as api_res:
            try:
                api_res_json = await api_res.json()
            except aiohttp.client.ContentTypeError:
                raise RuntimeError(await api_res.text())

    # Handle processing failure.
    if (api_res.status != 200 or
            api_res_json['results'][0]['status']['code'] == 'failure'):
        raise RuntimeError(await api_res.text())

    probs = api_res_json['results'][0]['entities'][0]['classes']
    return probs


def split_video_by_frames(cap: cv2.VideoCapture):
    """Split video by frames using OpenCV."""
    while cap.isOpened():
        success, image = cap.read()
        if not success:
            break
        yield image


async def main():
    """
    Script entry function.

    Open video, send video frame by frame to NSFW API and get probabilities for each frame
    that a frame is NSFW, blur frames that have high NSFW probability and write a new video.
    """
    args = parse_args()

    # Open a video
    cap = cv2.VideoCapture(str(args.input))
    fps = cap.get(cv2.CAP_PROP_FPS)
    size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
            int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    frames = list(split_video_by_frames(cap))

    print("Sending video to NSFW API.")
    # asyncio is used to speed up working with NSFW API by sending HTTP requests asynchronously.
    probs_frames = await asyncio.gather(
        *[is_frame_nsfw(frame, args.api_key)
          for frame in frames],
        return_exceptions=True
    )

    print("Blurring the video.")
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(str(args.output), fourcc, fps, size)
    for i, (prob, frame) in enumerate(zip(probs_frames, frames)):
        # If exception was thrown in is_frame_nsfw
        if issubclass(type(prob), Exception):
            print(f'Frame {i} was not handled. Reason: {prob}')
            out.write(frame)
            continue

        if prob['nsfw'] > THRESHOLD:
            out.write(cv2.blur(frame, (250, 250)))
        else:
            out.write(frame)

    out.release()
    cap.release()
    print(f'New video created: {args.output}.')

if __name__ == '__main__':
    asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

Testing the Script

Download the test video using the following link.

The video essentially contains only 4 different frames:

Image description

Run the script with the video. In case of successful execution you should see the following output:

python3 main.py --api-key a99264be8dmsh61090b802c2fc7dp1e0d48jsn42b0b9ff96fc --input ./nsfw.mp4 --output ./out2.mp4
Sending video to NSFW API.
Blurring the video.
New video created: out2.mp4.
Enter fullscreen mode Exit fullscreen mode

As a result, all frames containing NSFW content, will be completely blurred:

Image description

By following these steps, you can effectively blur NSFW content in your videos using the NSFW API from API4AI, ensuring your content remains appropriate for all audiences.

Conclusion

In this blog post, we discussed how to blur explicit content in videos using the NSFW API from API4AI. We started by understanding the importance of content moderation and the challenges of managing NSFW material. Then, we introduced the NSFW API, emphasizing its key features and benefits, such as high accuracy, speed, and ease of use.

We went through the process of setting up the NSFW API, including obtaining an API key from Rapid API Hub and verifying its functionality. Finally, we provided a detailed Python script that splits a video into frames, detects NSFW content, blurs the inappropriate frames, and reassembles the video.

By following this guide, you now have the tools and knowledge to effectively moderate content in your videos, ensuring a safer and more appropriate experience for your audience.

Now that you have a solid grasp of how to use the NSFW API, we encourage you to experiment with this powerful tool. Integrate it into your own projects and workflows to explore its full potential. You might discover additional use cases, such as real-time moderation for live streams or content filtering on user-generated content platforms.

Feel free to tweak the API's settings, such as the NSFW detection threshold, to better meet your specific needs. Try out different blurring techniques to see how they impact the user experience. The possibilities are vast, and by experimenting, you can find new ways to improve the safety and quality of your content.

As you continue to explore and utilize the NSFW API, don't hesitate to share your experiences, ask questions, and provide feedback. Your insights can benefit others in the community and contribute to the ongoing development of content moderation technologies.

By leveraging the NSFW API from API4AI, you are making significant strides toward maintaining a professional and respectful digital environment. Happy coding!

Additional Resources

To maximize your use of the NSFW API, here are some essential documentation links and resources:

  • NSFW API Documentation on Rapid API Hub: Access detailed information on using the NSFW API, including endpoints, parameters, and example requests.
  • API4AI Official Documentation: For comprehensive insights and examples on using various APIs provided by API4AI, visit their official documentation.
  • OpenCV Documentation: Since we used OpenCV for video processing, their official documentation can be helpful for understanding and expanding your video manipulation capabilities.

More stories about Image Processing Solutions

Top comments (0)