How to Blur Sexual Content in Any Video with the NSFW API

Introduction

In today's digital age, content moderation has become an essential aspect of 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 is more pressing than ever. Whether it's for social media platforms, educational tools, or content creation, ensuring that explicit content is appropriately moderated is crucial for protecting users and maintaining brand integrity.

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

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

Understanding NSFW Content

Definition

NSFW (Not Safe For Work) content refers to any material that is inappropriate for viewing in public or professional settings. This typically includes sexually explicit images or videos, but it can also encompass violent, profane, or otherwise offensive material. The need to manage NSFW content arises from the diverse audience that accesses digital platforms; what might be acceptable in one context can be highly inappropriate or offensive in another. Ensuring that such content is properly identified and moderated is crucial for maintaining a respectful and professional environment, protecting the reputation of digital platforms, and adhering to legal and regulatory standards.

Impact of NSFW Content

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

Content Moderation

Content moderation involves the processes and technologies used to detect, review, and manage NSFW content to prevent its inappropriate dissemination. There are various methods and tools available for content moderation, each with its strengths and limitations:

  • Manual Review: Involves human moderators reviewing content. While accurate, this method is time-consuming, costly, and not scalable for large volumes of content.

  • Automated Filters: Use algorithms to detect and filter NSFW content. These can be efficient but may lack the nuance and accuracy of human judgment.

  • AI and Machine Learning: Employ advanced AI models to identify NSFW content with high accuracy. These systems can process large amounts of data quickly and improve over time with more training.

Among these, the use of AI and machine learning has emerged as a powerful approach to content moderation. The NSFW API from API4AI exemplifies this by providing an efficient and reliable tool for detecting and managing NSFW content. With its high accuracy, speed, and ease of integration, the NSFW API offers a robust solution for ensuring that explicit content is appropriately moderated, making 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 use it effectively to blur NSFW content in videos.

Introduction to the NSFW API

What is the NSFW API?

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

Key Features

The NSFW API from API4AI comes packed with features that make it an ideal choice for content moderation:

  • Detection of NSFW Content: The primary function of the NSFW API is to accurately detect explicit material in videos and images. This includes identifying nudity, sexual acts, and other adult content.

  • High Accuracy: The API utilizes state-of-the-art machine learning models that have been trained on vast datasets, ensuring high accuracy in detecting NSFW content.

  • Speed: The NSFW API processes content quickly, making it suitable for real-time applications where rapid moderation is required.

  • Ease of Use: Designed with developers in mind, the API is straightforward to integrate into existing systems, with comprehensive documentation and support available.

  • Scalability: The API can handle large volumes of content, making it suitable for platforms with extensive user-generated content.

Advantages

Using the NSFW API from API4AI offers several advantages compared to traditional content moderation methods:

  • Efficiency: Automated detection reduces the need for manual review, saving time and resources. This is particularly beneficial for platforms with a high volume of user-generated content.

  • Consistency: Unlike human moderators, the API provides consistent results, eliminating subjective judgments and potential errors.

  • Real-Time Moderation: The speed of the NSFW API allows for real-time moderation, ensuring that inappropriate content is flagged or blurred almost instantly.

  • Cost-Effective: By reducing the reliance on human moderators, the NSFW API can lower operational costs associated with content moderation.

  • Improvement Over Time: The machine learning models behind the NSFW API continue to improve as they process more data, leading to increased accuracy and efficiency over time.

Incorporating the NSFW API into your content moderation strategy provides a robust, scalable, and efficient solution to managing explicit content, ensuring a safer and more user-friendly experience for your audience. In the next 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 start using the NSFW API to blur sexual content in videos, you need to ensure you have the following prerequisites:

  • API Key: You will need an API key to access the NSFW API. This can be obtained by subscribing to the API on Rapid API Hub.

  • Python: Ensure that Python is installed on your system. You can download it from the official Python website.

  • Python Libraries: Install 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

Subscribing to the API on Rapid API Hub

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

1. Create an Account on Rapid API Hub:

  • Go to the Rapid API Hub website.

  • Click on the "Sign Up" button if you don't have an account. If you already have an account, click "Log In".

  • Follow the prompts to create your account or log in.

2. Find the NSFW API:

  • Once logged in, use the search bar to look for "NSFW" or just follow this link.

  • Click on the NSFW API from the search results to go to the API's page.

3. Subscribe to the API:

  • Open the NSFW API page with subscription plans.

  • Choose a pricing plan that suits your needs (there may be a free tier available for testing purposes).

  • Complete the subscription process as prompted.

4. Obtain Your API Key:

  • After subscribing, navigate to the Dashboard.

  • On the left pat of the screen you should see something like “default-application_xxxxxx“.

  • Go to Autorization and copy Application Key

Rapid API Hub - obtaining API Key

Checking the API

Once you have subscribed to the NSFW API and obtained your API key, you need to verify that the API is working correctly. The simplest way to check the everything is OK is just executing the following command (just replace YOU_API_KEY with your API Key and image.jpg with the path to any image on your work station):

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

If you receive a successful response, it means the API is working correctly. Also refer to the API documentation for additional details.

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

Blurring Sexual Content in Videos with Python

Overview

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

Parse Command-Line Arguments

To make our script flexible and user-friendly, we'll use the argparse module to parse command-line arguments. This allows 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()

Split the Video into Frames

Next, we need to split the video into individual frames for processing. Function split_video_by_frames returns a generator that yields 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

Check if a Frame is Not Safe For Work

We'll create a function to check each frame for NSFW content using the NSFW API. This function will send each frame to the API and return a boolean indicating whether the frame contains NSFW content. The is_frame_nsfw function will be asynchronous to speed up video processing. is_frame_nsfw returns probabilities that the content is unsafe to work with. 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

Main Function

We'll combine the above functions in the main function to process the video: split it into frames, check each frame for NSFW content, blur the NSFW frames, and then reassemble 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())

Complete Python Code

Here is the complete Python script combining 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())

Testing the Script

Download the test video by the following link.

Basically it contains just 4 different frames:

Frames in original video for testing

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.

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

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

Summary

In this blog post, we explored how to blur sexual content in videos using the NSFW API from API4AI. We began by understanding the importance of content moderation and the challenges associated with managing NSFW content. Then, we introduced the NSFW API, highlighting its key features and advantages, such as high accuracy, speed, and ease of use.

We walked through the process of setting up the NSFW API, including obtaining an API key from Rapid API Hub and verifying the API's functionality. Finally, we provided a comprehensive 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 implement effective content moderation for your videos, ensuring a safer and more appropriate experience for your audience.

Encouragement to Experiment

Now that you have a working understanding of how to use the NSFW API, we encourage you to experiment with this powerful tool. Explore its potential by integrating it into your own projects and workflows. You might find additional use cases, such as real-time moderation for live streams or content filtering for user-generated content platforms.

Feel free to adjust the API's parameters, such as the NSFW detection threshold, to better suit your specific needs. Experiment with different blurring techniques and see how they affect the user experience. The possibilities are vast, and by experimenting, you can discover new ways to enhance the safety and quality of your content.

As you continue to explore and utilize the NSFW API, remember to share your experiences, ask questions, and provide feedback. Your insights can help others in the community and contribute to the ongoing improvement of content moderation technologies.

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

Additional Resources

To help you get the most out of the NSFW API, here are some essential documentation links and resources:

  • NSFW API Documentation on Rapid API Hub: Access detailed information on how to use the NSFW API, including endpoints, parameters, and example requests.

  • API4AI Official Documentation: For more comprehensive insights and examples on using various APIs offered by API4AI, visit their official documentation.

  • OpenCV Documentation: Since we used OpenCV for video processing, you might find their official documentation helpful for understanding and extending the video manipulation capabilities.

Previous
Previous

Detecting NSFW Images in PDFs Using Python and the NSFW API

Next
Next

From Pixels to Insights: How Image Processing Transforms Data Analytics