### Install from Repository with Keras 3 Source: https://github.com/bhky/opennsfw2/blob/main/README.md Clone the repository and install with Keras 3 support. ```shell git clone git@github.com:bhky/opennsfw2.git cd opennsfw2 python3 -m pip install ".[keras3]" ``` -------------------------------- ### Start FastAPI Service with Uvicorn Source: https://github.com/bhky/opennsfw2/blob/main/tests/integration/README.md Alternatively, start the FastAPI service using uvicorn. Ensure all dependencies from requirements-api.txt are installed. ```bash uvicorn app.main:app --host 0.0.0.0 --port 8000 ``` -------------------------------- ### Install from Repository with tf-keras Source: https://github.com/bhky/opennsfw2/blob/main/README.md Clone the repository and install with tf-keras support. ```shell git clone git@github.com:bhky/opennsfw2.git cd opennsfw2 python3 -m pip install ".[tf-keras]" ``` -------------------------------- ### Install Open-NSFW 2 with Keras Backend Source: https://context7.com/bhky/opennsfw2/llms.txt Install the library using pip, specifying the desired Keras backend. Environment variables can control the backend or weight cache location. ```bash # Keras 3 with TensorFlow backend (recommended) pip install "opennsfw2[keras3]" # tf-keras (TensorFlow-integrated Keras) pip install "opennsfw2[tf-keras]" # Force tf-keras when both versions are installed OPENNSFW2_KERAS=tf-keras python3 your_script.py # Control where pre-trained weights are cached OPENNSFW2_HOME=/custom/dir python3 your_script.py ``` -------------------------------- ### Install Dependencies and Run API Directly Source: https://github.com/bhky/opennsfw2/blob/main/README-HTTP.md Install the required Python dependencies and then run the FastAPI application using uvicorn. ```bash pip install -r requirements-api.txt uvicorn app.main:app --host 0.0.0.0 --port 8000 ``` -------------------------------- ### Start FastAPI Service Source: https://github.com/bhky/opennsfw2/blob/main/tests/integration/README.md Use Docker to start the FastAPI service on port 8000. Ensure all dependencies from requirements-api.txt are installed. ```bash docker run -p 8000:8000 opennsfw2-api ``` -------------------------------- ### Start Open-NSFW 2 Service Source: https://context7.com/bhky/opennsfw2/llms.txt Use Docker to build and run the Open-NSFW 2 API service, or use uvicorn for direct execution. ```bash # Start the service docker build -t opennsfw2-api . && docker run -p 8000:8000 opennsfw2-api # Or: uvicorn app.main:app --host 0.0.0.0 --port 8000 ``` -------------------------------- ### Install OpenNSFW2 with Keras 3 Source: https://github.com/bhky/opennsfw2/blob/main/README.md Install the package with the Keras 3 backend support using pip. ```shell python3 -m pip install "opennsfw2[keras3]" ``` -------------------------------- ### Install OpenNSFW2 with tf-keras Source: https://github.com/bhky/opennsfw2/blob/main/README.md Install the package with the tf-keras backend support using pip. ```shell python3 -m pip install "opennsfw2[tf-keras]" ``` -------------------------------- ### Model Readiness Probe Source: https://context7.com/bhky/opennsfw2/llms.txt Check if the model weights are loaded by sending a GET request to the /health/model endpoint. A successful response indicates the model is ready for predictions. ```bash # Model readiness probe (confirms weights are loaded) curl -s http://localhost:8000/health/model # { "status": "ok", "model_loaded": true } ``` -------------------------------- ### Basic Liveness Probe Source: https://context7.com/bhky/opennsfw2/llms.txt Perform a basic liveness check on the service by sending a GET request to the /health/ endpoint. A successful response returns a JSON object with status 'ok'. ```bash # Basic liveness probe curl -s http://localhost:8000/health/ # { "status": "ok" } ``` -------------------------------- ### Image Prediction Response Format Source: https://github.com/bhky/opennsfw2/blob/main/README-HTTP.md Example JSON structure for a successful single image prediction response, including NSFW probability, processing time, and API version. ```json { "result": { "nsfw_probability": 0.85 }, "processing_time_ms": 245.5, "version": "" } ``` -------------------------------- ### Predict NSFW Probabilities of Multiple Images Source: https://github.com/bhky/opennsfw2/blob/main/README.md Efficiently get NSFW probabilities for a list of images. This method is optimized for batch processing. ```APIDOC ## predict_images ### Description Calculates the NSFW probabilities for a list of images. This is more efficient than calling `predict_image` in a loop. ### Parameters - **image_handles** (list[str or PIL.Image.Image]) - A list of image file paths or PIL Image objects. ### Returns - **nsfw_probabilities** (list[float]) - A list of NSFW probabilities corresponding to the input images. ``` -------------------------------- ### Video Prediction Response Format Source: https://github.com/bhky/opennsfw2/blob/main/README-HTTP.md Example JSON structure for a successful video prediction response, detailing elapsed seconds and NSFW probabilities for frames, along with processing time and API version. ```json { "result": { "elapsed_seconds": [0.0, 0.125, 0.25, ...], "nsfw_probabilities": [0.1, 0.15, 0.8, ...] }, "processing_time_ms": 15000.0, "version": "" } ``` -------------------------------- ### Predict NSFW Probabilities of Multiple Images Source: https://github.com/bhky/opennsfw2/blob/main/README.md Efficiently get NSFW probabilities for a list of images. Provide a list of file paths or PIL Image objects. This method is optimized for batching and single model instantiation. ```python import opennsfw2 as n2 image_handles = [ "path/to/your/image1.jpg", "path/to/your/image2.jpg", # ... ] nsfw_probabilities = n2.predict_images(image_handles) ``` -------------------------------- ### Predict NSFW Probability of a Single Image Source: https://github.com/bhky/opennsfw2/blob/main/README.md Get the NSFW probability of a single image by providing its file path or a PIL Image object. ```APIDOC ## predict_image ### Description Calculates the NSFW probability for a single image. ### Parameters - **image_handle** (str or PIL.Image.Image) - Path to the image file or a PIL Image object. ### Returns - **nsfw_probability** (float) - The NSFW probability of the image. ``` -------------------------------- ### Analyze Video Frames for NSFW Content Source: https://context7.com/bhky/opennsfw2/llms.txt Process video frames using `predict_video_frames` to get NSFW probabilities per frame, with options for frame interval, aggregation, and output video annotation. Probabilities are aggregated over sliding windows to reduce noise. ```python import opennsfw2 as n2 elapsed_secs, nsfw_probs = n2.predict_video_frames( video_path="clip.mp4", frame_interval=8, # predict every 8th frame aggregation_size=8, # aggregate over 8 frames per window aggregation=n2.Aggregation.MEAN, # MEAN | MEDIAN | MAX | MIN batch_size=8, output_video_path="clip_annotated.mp4", # optional annotated output preprocessing=n2.Preprocessing.YAHOO, progress_bar=True ) # Find the peak NSFW moment peak_idx = nsfw_probs.index(max(nsfw_probs)) print(f"Peak NSFW at {elapsed_secs[peak_idx]:.2f}s: {nsfw_probs[peak_idx]:.4f}") # Detect NSFW segments (probability >= 0.8) nsfw_segments = [ (elapsed_secs[i], nsfw_probs[i]) for i, p in enumerate(nsfw_probs) if p >= 0.8 ] print(f"NSFW segments: {nsfw_segments[:5]}") ``` -------------------------------- ### Python Client for Image Prediction Source: https://github.com/bhky/opennsfw2/blob/main/README-HTTP.md Python functions using the `requests` library to perform single image predictions via URL or Base64 encoding. Includes example usage and result printing. ```python import requests import base64 # Single image prediction. def predict_image_url(url: str) -> dict: response = requests.post( "http://localhost:8000/predict/image", json={ "input": { "type": "url", "data": url } } ) return response.json() # Base64 image prediction. def predict_image_base64(image_path: str) -> dict: with open(image_path, "rb") as f: image_data = base64.b64encode(f.read()).decode() response = requests.post( "http://localhost:8000/predict/image", json={ "input": { "type": "base64", "data": image_data } } ) return response.json() # Usage. result = predict_image_url("https://example.com/image.jpg") print(f"NSFW probability: {result['result']['nsfw_probability']}") ``` -------------------------------- ### Predict NSFW Probabilities of Video Frames Source: https://github.com/bhky/opennsfw2/blob/main/README.md Analyze a video file to get NSFW probabilities for each frame. The video can be in any format supported by OpenCV. Returns elapsed time and probabilities. ```python import opennsfw2 as n2 video_path = "path/to/your/video.mp4" elapsed_seconds, nsfw_probabilities = n2.predict_video_frames(video_path) ``` -------------------------------- ### Predict NSFW Probability of a Single Image Source: https://github.com/bhky/opennsfw2/blob/main/README.md Get the NSFW probability for a single image by providing its file path or a PIL Image object. This function handles model loading and prediction. ```python import opennsfw2 as n2 image_handle = "path/to/your/image.jpg" nsfw_probability = n2.predict_image(image_handle) ``` -------------------------------- ### Build and Run Docker Image Source: https://github.com/bhky/opennsfw2/blob/main/README-HTTP.md Use these commands to build the Docker image and run the API service. Alternatively, `docker compose up` can be used. ```bash docker build -t opennsfw2-api . docker run -p 8000:8000 opennsfw2-api ``` ```bash docker compose up opennsfw2-api ``` -------------------------------- ### Run All Code Checks and Unit Tests Source: https://github.com/bhky/opennsfw2/blob/main/tests/README.md Execute all code quality checks and unit tests for the project. This is the recommended command for a comprehensive test run. ```bash # Run all code quality checks + unit tests. bash tests/run_code_checks.sh ``` -------------------------------- ### Create and Compile OpenNSFW Model Source: https://github.com/bhky/opennsfw2/blob/main/README.md Initializes the OpenNSFW model with pre-trained weights and compiles it for training. The default behavior loads pre-trained weights; pass `weights_path=None` to train from scratch. ```python # For fine-tuning, load the pre-trained weights (default behaviour). # For training from scratch, pass weights_path=None. model = n2.make_open_nsfw_model() # Compile and train. model.compile( optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"], ) model.fit(dataset, epochs=10) ``` -------------------------------- ### Prepare Data for Training/Fine-tuning Source: https://github.com/bhky/opennsfw2/blob/main/README.md Prepare lists of image file paths and corresponding labels (0 for SFW, 1 for NSFW) for use in training or fine-tuning the model with the TensorFlow backend. ```python import opennsfw2 as n2 import tensorflow as tf image_paths = [ "path/to/your/image1.jpg", "path/to/your/image2.jpg", # ... ] labels = [0, 1, ...] ``` -------------------------------- ### Select Image Preprocessing Strategy Source: https://context7.com/bhky/opennsfw2/llms.txt Choose between `YAHOO` (default, for pre-trained model compatibility) and `SIMPLE` (direct resize, different probability scale) preprocessing strategies using the `Preprocessing` enum. ```python import opennsfw2 as n2 print(list(n2.Preprocessing)) # [, ] # Use YAHOO for pre-trained model compatibility prob_yahoo = n2.predict_image("photo.jpg", preprocessing=n2.Preprocessing.YAHOO) # Use SIMPLE for a more intuitive pipeline (different probability scale) prob_simple = n2.predict_image("photo.jpg", preprocessing=n2.Preprocessing.SIMPLE) print(f"YAHOO: {prob_yahoo:.4f}, SIMPLE: {prob_simple:.4f}") ``` -------------------------------- ### make_open_nsfw_model Source: https://github.com/bhky/opennsfw2/blob/main/README.md Creates an instance of the NSFW model, with options to load pre-trained weights. ```APIDOC ## make_open_nsfw_model ### Description Create an instance of the NSFW model, optionally with pre-trained weights from Yahoo. ### Parameters - `input_shape` (Tuple[int, int, int], default (224, 224, 3)): Input shape of the model, this should not be changed. - `weights_path` (Optional[str], default $HOME/.opennsfw/weights/open_nsfw_weights.h5): Path to the weights in HDF5 format to be loaded by the model. The weights file will be downloaded if not exists. If `None`, no weights will be downloaded nor loaded to the model. Users can provide path if the default is not preferred. The environment variable `OPENNSFW2_HOME` can also be used to indicate where the `.opennsfw2/` directory should be located. - `name` (str, default `opennsfw2`): Model name to be used for the Keras model object. ### Return - `keras.Model` object. ``` -------------------------------- ### Build tf.data Pipeline with Preprocessing Source: https://github.com/bhky/opennsfw2/blob/main/README.md Constructs a tf.data pipeline for image loading and preprocessing. Use `tf.data.AUTOTUNE` for optimal performance in map and prefetch operations. ```python dataset = tf.data.Dataset.from_tensor_slices((image_paths, labels)) def load_and_preprocess(image_path, label): image = tf.io.read_file(image_path) image = tf.io.decode_jpeg(image, channels=3) # The preprocessed image is a tensor of shape (224, 224, 3). image = n2.preprocess_image_tensor(image, n2.Preprocessing.YAHOO) return image, label dataset = ( dataset .map(load_and_preprocess, num_parallel_calls=tf.data.AUTOTUNE) .batch(32) .prefetch(tf.data.AUTOTUNE) ) ``` -------------------------------- ### Preprocess Image for Model Input Source: https://context7.com/bhky/opennsfw2/llms.txt Applies preprocessing to a PIL Image, converting it to a NumPy array suitable for model input. Choose between YAHOO (default, includes JPEG round-trip) or SIMPLE (direct resize) pipelines. Both convert RGB to BGR and subtract VGG channel mean. ```python import numpy as np import opennsfw2 as n2 from PIL import Image pil_img = Image.open("photo.jpg") # YAHOO preprocessing (original pipeline, recommended for pre-trained weights) image_yahoo = n2.preprocess_image(pil_img, n2.Preprocessing.YAHOO) print(image_yahoo.shape) # (224, 224, 3) print(image_yahoo.dtype) # float32 # SIMPLE preprocessing image_simple = n2.preprocess_image(pil_img, n2.Preprocessing.SIMPLE) # Manual inference using the preprocessed array model = n2.make_open_nsfw_model() batch = np.expand_dims(image_yahoo, axis=0) # shape: (1, 224, 224, 3) predictions = model.predict(batch) # shape: (1, 2) sfw_prob, nsfw_prob = predictions[0] print(f"SFW: {sfw_prob:.4f}, NSFW: {nsfw_prob:.4f}") ``` -------------------------------- ### Preprocess Image for Model Input Source: https://github.com/bhky/opennsfw2/blob/main/README.md Prepares a PIL Image object for input into the OpenNSFW model. ```APIDOC ## preprocess_image ### Description Resizes and normalizes a PIL Image to the format expected by the OpenNSFW model (e.g., 224x224 pixels with specific channel ordering). ### Parameters - **pil_image** (PIL.Image.Image) - The image object to preprocess. - **preprocessing_type** (opennsfw2.Preprocessing) - The type of preprocessing to apply (e.g., `opennsfw2.Preprocessing.YAHOO`). ### Returns - **image** (numpy.ndarray) - The preprocessed image as a NumPy array. ``` -------------------------------- ### Create and Fine-tune OpenNSFW Model Source: https://context7.com/bhky/opennsfw2/llms.txt Constructs the Open-NSFW Keras model. By default, it loads pre-trained Yahoo weights. Pass `weights_path=None` for training from scratch. Supports standard Keras methods like `.predict`, `.fit`, and `.save`. ```python import opennsfw2 as n2 # Default: load pre-trained weights (auto-download if absent) model = n2.make_open_nsfw_model() model.summary() # Output layer: predictions (softmax, 2 units) → [sfw_prob, nsfw_prob] # Custom weights path model = n2.make_open_nsfw_model( weights_path="/models/open_nsfw_weights.h5" ) # No weights (train from scratch) model_scratch = n2.make_open_nsfw_model(weights_path=None) # Fine-tuning on custom data model_scratch.compile( optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"], ) model_scratch.fit(dataset, epochs=10) # dataset from preprocess_image_tensor example # Save fine-tuned weights model_scratch.save_weights("finetuned_nsfw_weights.h5") ``` -------------------------------- ### Create and Use OpenNSFW2 Keras Model Source: https://github.com/bhky/opennsfw2/blob/main/README.md Instantiate the OpenNSFW model, which automatically downloads pre-trained weights if not found locally. Make predictions on preprocessed image data. ```python import numpy as np import opennsfw2 as n2 from PIL import Image image_path = "path/to/your/image.jpg" pil_image = Image.open(image_path) image = n2.preprocess_image(pil_image, n2.Preprocessing.YAHOO) model = n2.make_open_nsfw_model() inputs = np.expand_dims(image, axis=0) predictions = model.predict(inputs) sfw_probability, nsfw_probability = predictions[0] ``` -------------------------------- ### Load and Preprocess Image for Keras Model Source: https://github.com/bhky/opennsfw2/blob/main/README.md Load an image using PIL and preprocess it into a NumPy array suitable for the OpenNSFW model using the YAHOO preprocessing method. ```python import numpy as np import opennsfw2 as n2 from PIL import Image image_path = "path/to/your/image.jpg" pil_image = Image.open(image_path) image = n2.preprocess_image(pil_image, n2.Preprocessing.YAHOO) ``` -------------------------------- ### Make OpenNSFW Model Source: https://github.com/bhky/opennsfw2/blob/main/README.md Creates an instance of the OpenNSFW Keras model with pre-trained weights. ```APIDOC ## make_open_nsfw_model ### Description Initializes and returns a Keras model for NSFW detection. It automatically handles downloading pre-trained weights if they are not found locally. ### Returns - **model** (keras.Model) - The configured OpenNSFW Keras model. ``` -------------------------------- ### Run API Integration Test Against Different URL Source: https://github.com/bhky/opennsfw2/blob/main/tests/integration/README.md Run the integration tests against a FastAPI service running on a different URL. Ensure the API server is running. ```python python tests/integration/test_api_integration.py http://localhost:8001 ``` -------------------------------- ### preprocess_image Source: https://context7.com/bhky/opennsfw2/llms.txt Applies a preprocessing pipeline to a PIL Image, returning a NumPy array ready for model input. Supports YAHOO and SIMPLE preprocessing strategies. ```APIDOC ## preprocess_image Applies the preprocessing pipeline to a single `PIL.Image.Image` and returns a NumPy array of shape `(224, 224, 3)` ready for model input. Two pipelines are available: `YAHOO` (default, matches the original Caffe/TensorFlow 1 pipeline including a JPEG round-trip) and `SIMPLE` (direct resize without JPEG artefacts). Both convert RGB to BGR and subtract the VGG channel mean `[104, 117, 123]`. ```python import numpy as np import opennsfw2 as n2 from PIL import Image pil_img = Image.open("photo.jpg") # YAHOO preprocessing (original pipeline, recommended for pre-trained weights) image_yahoo = n2.preprocess_image(pil_img, n2.Preprocessing.YAHOO) print(image_yahoo.shape) # (224, 224, 3) print(image_yahoo.dtype) # float32 # SIMPLE preprocessing image_simple = n2.preprocess_image(pil_img, n2.Preprocessing.SIMPLE) # Manual inference using the preprocessed array model = n2.make_open_nsfw_model() batch = np.expand_dims(image_yahoo, axis=0) # shape: (1, 224, 224, 3) predictions = model.predict(batch) # shape: (1, 2) sfw_prob, nsfw_prob = predictions[0] print(f"SFW: {sfw_prob:.4f}, NSFW: {nsfw_prob:.4f}") ``` ``` -------------------------------- ### Predict Batch Images from URLs Source: https://context7.com/bhky/opennsfw2/llms.txt Send a POST request to the /predict/images endpoint with a JSON body containing a list of image URLs for batch prediction. The response provides NSFW probabilities for each image in the order they were provided. ```bash curl -s -X POST "http://localhost:8000/predict/images" \ -H "Content-Type: application/json" \ -d '{ "inputs": [ { "type": "url", "data": "https://example.com/photo1.jpg" }, { "type": "url", "data": "https://example.com/photo2.jpg" } ], "options": { "preprocessing": "YAHOO" } }' | python3 -m json.tool ``` -------------------------------- ### Predict Video from URL Source: https://context7.com/bhky/opennsfw2/llms.txt Send a POST request to the /predict/video endpoint with a JSON body containing a video URL for NSFW detection. The response includes lists of elapsed seconds and NSFW probabilities for each frame. ```bash curl -s -X POST "http://localhost:8000/predict/video" \ -H "Content-Type: application/json" \ -d '{ "input": { "type": "url", "data": "https://example.com/clip.mp4" }, "options": { "preprocessing": "YAHOO", "frame_interval": 8, "aggregation_size": 8, "aggregation": "MEAN" } }' | python3 -m json.tool ``` -------------------------------- ### Force tf-keras Backend Source: https://github.com/bhky/opennsfw2/blob/main/README.md Set the environment variable OPENNSFW2_KERAS to 'tf-keras' to force its usage before importing the library. ```shell OPENNSFW2_KERAS=tf-keras python3 your_script.py ``` -------------------------------- ### Run Unit Tests Only Source: https://github.com/bhky/opennsfw2/blob/main/tests/README.md Execute only the unit tests for the OpenNSFW2 library. This command uses Python's built-in unittest module to discover and run tests. ```python # Run just the unit tests. python -m unittest discover tests/unit ``` -------------------------------- ### Run API Integration Test Source: https://github.com/bhky/opennsfw2/blob/main/tests/integration/README.md Execute the integration tests for the FastAPI HTTP service. These tests require the API server to be running. ```python python tests/integration/test_api_integration.py ``` -------------------------------- ### preprocess_image Source: https://github.com/bhky/opennsfw2/blob/main/README.md Applies necessary preprocessing to an input image, returning a NumPy array suitable for model input. ```APIDOC ## preprocess_image ### Description Apply necessary preprocessing to the input image. ### Parameters - `pil_image` (PIL.Image.Image): Input as a Pillow image. - `preprocessing` (Preprocessing enum, default Preprocessing.YAHOO): See [preprocessing details](#preprocessing-details). ### Return - NumPy array of shape (224, 224, 3). ``` -------------------------------- ### Predict Single Image from URL Source: https://context7.com/bhky/opennsfw2/llms.txt Send a POST request to the /predict/image endpoint with a JSON body containing a URL for image prediction. The response includes NSFW probability, processing time, and version. ```bash # Predict from URL curl -s -X POST "http://localhost:8000/predict/image" \ -H "Content-Type: application/json" \ -d '{ "input": { "type": "url", "data": "https://example.com/photo.jpg" }, "options": { "preprocessing": "YAHOO" } }' | python3 -m json.tool ``` -------------------------------- ### Predict Multiple Images Source: https://github.com/bhky/opennsfw2/blob/main/README-HTTP.md Send a POST request to the `/predict/images` endpoint with a JSON payload containing a list of image inputs (URLs or Base64) and optional preprocessing options. ```bash curl -X POST "http://localhost:8000/predict/images" \ -H "Content-Type: application/json" \ -d '{ "inputs": [ { "type": "url", "data": "https://example.com/image1.jpg" }, { "type": "url", "data": "https://example.com/image2.jpg" } ], "options": { "preprocessing": "YAHOO" } }' ``` -------------------------------- ### Preprocessing Enum Source: https://context7.com/bhky/opennsfw2/llms.txt Enum to select the image preprocessing strategy. YAHOO is recommended for pre-trained models, while SIMPLE offers a different probability scale. ```APIDOC ## Preprocessing Enum Selects the image preprocessing strategy. `YAHOO` is the default and is required for accurate results with the pre-trained weights. `SIMPLE` skips the JPEG round-trip step and produces different probability values. ```python import opennsfw2 as n2 print(list(n2.Preprocessing)) # [, ] # Use YAHOO for pre-trained model compatibility prob_yahoo = n2.predict_image("photo.jpg", preprocessing=n2.Preprocessing.YAHOO) # Use SIMPLE for a more intuitive pipeline (different probability scale) prob_simple = n2.predict_image("photo.jpg", preprocessing=n2.Preprocessing.SIMPLE) print(f"YAHOO: {prob_yahoo:.4f}, SIMPLE: {prob_simple:.4f}") ``` ``` -------------------------------- ### Predict Single Image via URL Source: https://github.com/bhky/opennsfw2/blob/main/README-HTTP.md Send a POST request to the `/predict/image` endpoint with a JSON payload containing the image URL and optional preprocessing options. ```bash curl -X POST "http://localhost:8000/predict/image" \ -H "Content-Type: application/json" \ -d '{ "input": { "type": "url", "data": "https://example.com/image.jpg" }, "options": { "preprocessing": "YAHOO" } }' ``` -------------------------------- ### POST /predict/images Source: https://context7.com/bhky/opennsfw2/llms.txt Performs batch NSFW prediction on multiple images. Accepts a JSON body with an 'inputs' list, where each item specifies either a 'url' or a 'base64'-encoded image. Returns a list of NSFW probabilities in the same order as the input. ```APIDOC ## POST /predict/images ### Description Batch image prediction over the HTTP service. Accepts a list of `inputs` (each `url` or `base64`) and returns a list of NSFW probabilities in the same order. ### Method POST ### Endpoint /predict/images ### Parameters #### Request Body - **inputs** (array) - Required - A list of image input objects. - Each object in the array should have: - **type** (string) - Required - Type of input, either "url" or "base64". - **data** (string) - Required - The image URL or base64-encoded image data. - **options** (object) - Optional - Additional processing options. - **preprocessing** (string) - Optional - Preprocessing method (e.g., "YAHOO"). ### Request Example ```json { "inputs": [ { "type": "url", "data": "https://example.com/photo1.jpg" }, { "type": "url", "data": "https://example.com/photo2.jpg" } ], "options": { "preprocessing": "YAHOO" } } ``` ### Response #### Success Response (200) - **result** (object) - Contains the prediction results. - **nsfw_probabilities** (array of numbers) - A list of NSFW probability scores corresponding to the input images. - **processing_time_ms** (number) - The time taken for processing in milliseconds. - **version** (string) - The version of the library used. #### Response Example ```json { "result": { "nsfw_probabilities": [0.0312, 0.9514] }, "processing_time_ms": 312.7, "version": "0.18.0" } ``` ``` -------------------------------- ### predict_images Source: https://context7.com/bhky/opennsfw2/llms.txt Performs NSFW prediction on a batch of images, accepting lists of file paths or PIL Image objects. This is more efficient than calling `predict_image` multiple times. ```APIDOC ## predict_images ### Description Batch version of `predict_image`. Accepts a list of file paths or PIL images and returns a list of NSFW probabilities. The model is instantiated only once and inference is done in configurable batches, making this significantly faster than calling `predict_image` in a loop. ### Parameters - **image_paths_or_objects** (list[str | PIL.Image.Image]) - A list of image file paths or PIL Image objects. - **batch_size** (int, optional) - The number of images to process in each batch. Defaults to 8. - **preprocessing** (Preprocessing, optional) - The preprocessing method to use. Defaults to `Preprocessing.YAHOO`. - **grad_cam_paths** (list[str], optional) - A list of paths to save Grad-CAM overlay images for each input image. Only supported by the TensorFlow backend. - **alpha** (float, optional) - Opacity of the heatmap overlay for Grad-CAM. Defaults to 0.8. ### Returns - **nsfw_probs** (list[float]) - A list of NSFW probabilities corresponding to the input images. ### Request Example ```python import opennsfw2 as n2 image_paths = [ "images/photo1.jpg", "images/photo2.png", "images/photo3.jpg", ] # --- Basic batch prediction --- nsfw_probs = n2.predict_images(image_paths, batch_size=8) for path, prob in zip(image_paths, nsfw_probs): label = "NSFW" if prob >= 0.8 else "SFW" print(f"{path}: {prob:.4f} ({label})") # --- With Grad-CAM overlays (TensorFlow backend only) --- cam_paths = ["cam1.jpg", "cam2.jpg", "cam3.jpg"] nsfw_probs = n2.predict_images( image_paths, batch_size=16, preprocessing=n2.Preprocessing.YAHOO, grad_cam_paths=cam_paths, alpha=0.8 ) ``` ### Response Example ``` images/photo1.jpg: 0.0234 (SFW) images/photo2.png: 0.9712 (NSFW) images/photo3.jpg: 0.1105 (SFW) ``` ``` -------------------------------- ### make_open_nsfw_model Source: https://context7.com/bhky/opennsfw2/llms.txt Constructs the ResNet-based Open-NSFW Keras model. Optionally loads pre-trained weights or creates an untrained model for custom training. ```APIDOC ## make_open_nsfw_model Constructs the ResNet-based Open-NSFW Keras model. By default the pre-trained Yahoo weights are downloaded and loaded automatically. Passing `weights_path=None` returns an untrained model suitable for training from scratch. The returned object is a standard `keras.Model` and supports all standard Keras methods (`.predict`, `.fit`, `.save`, etc.). ```python import opennsfw2 as n2 # Default: load pre-trained weights (auto-download if absent) model = n2.make_open_nsfw_model() model.summary() # Output layer: predictions (softmax, 2 units) → [sfw_prob, nsfw_prob] # Custom weights path model = n2.make_open_nsfw_model( weights_path="/models/open_nsfw_weights.h5" ) # No weights (train from scratch) model_scratch = n2.make_open_nsfw_model(weights_path=None) # Fine-tuning on custom data model_scratch.compile( optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"], ) model_scratch.fit(dataset, epochs=10) # dataset from preprocess_image_tensor example # Save fine-tuned weights model_scratch.save_weights("finetuned_nsfw_weights.h5") ``` ``` -------------------------------- ### Batch Predict NSFW Probabilities for Multiple Images Source: https://context7.com/bhky/opennsfw2/llms.txt Utilize `predict_images` for efficient batch processing of multiple image paths or PIL Images. This method instantiates the model once and uses configurable batch sizes for faster inference compared to looping `predict_image`. ```python import opennsfw2 as n2 image_paths = [ "images/photo1.jpg", "images/photo2.png", "images/photo3.jpg", ] # --- Basic batch prediction --- nsfw_probs = n2.predict_images(image_paths, batch_size=8) for path, prob in zip(image_paths, nsfw_probs): label = "NSFW" if prob >= 0.8 else "SFW" print(f"{path}: {prob:.4f} ({label})") # images/photo1.jpg: 0.0234 (SFW) # images/photo2.png: 0.9712 (NSFW) # images/photo3.jpg: 0.1105 (SFW) # --- With Grad-CAM overlays (TensorFlow backend only) --- cam_paths = ["cam1.jpg", "cam2.jpg", "cam3.jpg"] nsfw_probs = n2.predict_images( image_paths, batch_size=16, preprocessing=n2.Preprocessing.YAHOO, grad_cam_paths=cam_paths, alpha=0.8 ) ``` -------------------------------- ### Health Endpoints Source: https://context7.com/bhky/opennsfw2/llms.txt Provides health check endpoints for load-balancer probes and model-readiness checks. ```APIDOC ## Health Endpoints ### Description Two health-check endpoints allow load-balancer probes and model-readiness checks. ### Endpoints #### GET /health/ ##### Description Basic liveness probe. ##### Response - **status** (string) - Indicates the status, typically "ok". ##### Response Example ```json { "status": "ok" } ``` #### GET /health/model ##### Description Model readiness probe, confirms if model weights are loaded. ##### Response - **status** (string) - Indicates the status, typically "ok". - **model_loaded** (boolean) - True if the model is loaded, false otherwise. ##### Response Example ```json { "status": "ok", "model_loaded": true } ``` ``` -------------------------------- ### Predict Video Source: https://github.com/bhky/opennsfw2/blob/main/README-HTTP.md Send a POST request to the `/predict/video` endpoint with a JSON payload containing the video URL and options for frame processing and aggregation. ```bash curl -X POST "http://localhost:8000/predict/video" \ -H "Content-Type: application/json" \ -d '{ "input": { "type": "url", "data": "https://example.com/video.mp4" }, "options": { "preprocessing": "YAHOO", "frame_interval": 8, "aggregation_size": 8, "aggregation": "MEAN" } }' ``` -------------------------------- ### preprocess_image_tensor Source: https://github.com/bhky/opennsfw2/blob/main/README.md Provides a tensor-based preprocessing function for use in dataset pipelines like tf.data.Dataset.map. ```APIDOC ## preprocess_image_tensor ### Description Tensor-based preprocessing equivalent of `preprocess_image`, suitable for use with dataset pipelines (e.g., `tf.data.Dataset.map`). Note that the JPEG round-trip in the `YAHOO` pipeline is intentionally omitted. ### Parameters - `image` (Keras tensor of shape (H, W, C), uint8): Input as a single RGB image tensor. - `preprocessing` (Preprocessing enum, default Preprocessing.YAHOO): See [preprocessing details](#preprocessing-details). ### Return - Keras tensor of shape (224, 224, 3). ``` -------------------------------- ### Control Video Frame Aggregation Source: https://context7.com/bhky/opennsfw2/llms.txt Use the `Aggregation` enum to control how per-frame NSFW probabilities are aggregated. `MEAN` (default) is for general moderation, `MAX` flags clips with any explicit frame, and `MEDIAN` is robust to outliers. ```python import opennsfw2 as n2 print(list(n2.Aggregation)) # [, , # , ] # MAX aggregation: flag if any frame in the window is NSFW elapsed, probs = n2.predict_video_frames( "clip.mp4", aggregation=n2.Aggregation.MAX, frame_interval=4, aggregation_size=4, ) # MEDIAN aggregation: robust to individual outlier frames elapsed, probs = n2.predict_video_frames( "clip.mp4", aggregation=n2.Aggregation.MEDIAN, ) ``` -------------------------------- ### Predict NSFW Probabilities of Video Frames Source: https://github.com/bhky/opennsfw2/blob/main/README.md Analyze a video file and return the elapsed time and NSFW probability for each frame. ```APIDOC ## predict_video_frames ### Description Analyzes each frame of a video to determine its NSFW probability. ### Parameters - **video_path** (str) - The path to the video file (supported by OpenCV). ### Returns - **elapsed_seconds** (list[float]) - A list of elapsed times in seconds for each frame. - **nsfw_probabilities** (list[float]) - A list of NSFW probabilities for each frame. ``` -------------------------------- ### Python Client for Batch Image Prediction Source: https://context7.com/bhky/opennsfw2/llms.txt A Python function to perform batch image prediction using the /predict/images endpoint. It reads local image files, encodes them to base64, and sends them in a POST request. ```python # Python client equivalent import requests, base64 def batch_predict(image_paths: list[str]) -> list[float]: inputs = [] for path in image_paths: with open(path, "rb") as f: inputs.append({ "type": "base64", "data": base64.b64encode(f.read()).decode() }) resp = requests.post( "http://localhost:8000/predict/images", json={"inputs": inputs, "options": {"preprocessing": "YAHOO"}} ) resp.raise_for_status() return resp.json()["result"]["nsfw_probabilities"] probs = batch_predict(["photo1.jpg", "photo2.jpg"]) print(probs) # [0.0312, 0.9514] ``` -------------------------------- ### POST /predict/image Source: https://context7.com/bhky/opennsfw2/llms.txt Performs NSFW prediction on a single image. Accepts a JSON body with an 'input' object specifying either a 'url' or a 'base64'-encoded image. Returns the NSFW probability, processing time, and library version. ```APIDOC ## POST /predict/image ### Description Single-image NSFW prediction via the FastAPI HTTP service. Accepts a JSON body with an `input` object specifying either a `url` or a `base64`-encoded image. Returns the NSFW probability, processing time, and library version. ### Method POST ### Endpoint /predict/image ### Request Body - **input** (object) - Required - Specifies the image source. - **type** (string) - Required - Type of input, either "url" or "base64". - **data** (string) - Required - The image URL or base64-encoded image data. - **options** (object) - Optional - Additional processing options. - **preprocessing** (string) - Optional - Preprocessing method (e.g., "YAHOO"). ### Request Example ```json { "input": { "type": "url", "data": "https://example.com/photo.jpg" }, "options": { "preprocessing": "YAHOO" } } ``` ### Response #### Success Response (200) - **result** (object) - Contains the prediction results. - **nsfw_probability** (number) - The NSFW probability score. - **processing_time_ms** (number) - The time taken for processing in milliseconds. - **version** (string) - The version of the library used. #### Response Example ```json { "result": { "nsfw_probability": 0.0312 }, "processing_time_ms": 183.4, "version": "0.18.0" } ``` ``` -------------------------------- ### Predict Single Image via Base64 Source: https://github.com/bhky/opennsfw2/blob/main/README-HTTP.md Send a POST request to the `/predict/image` endpoint with a JSON payload containing the Base64 encoded image data. ```bash curl -X POST "http://localhost:8000/predict/image" \ -H "Content-Type: application/json" \ -d '{ "input": { "type": "base64", "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==" } }' ``` -------------------------------- ### POST /predict/video Source: https://context7.com/bhky/opennsfw2/llms.txt Performs NSFW detection on a video. Accepts a JSON body with an 'input' object specifying either a 'url' or 'base64'-encoded video. Returns parallel lists of elapsed seconds and NSFW probabilities for each frame. ```APIDOC ## POST /predict/video ### Description Video NSFW detection via the HTTP service. Accepts a `url` or `base64` video and returns parallel lists of elapsed seconds and NSFW probabilities for each frame. ### Method POST ### Endpoint /predict/video ### Parameters #### Request Body - **input** (object) - Required - Specifies the video source. - **type** (string) - Required - Type of input, either "url" or "base64". - **data** (string) - Required - The video URL or base64-encoded video data. - **options** (object) - Optional - Additional processing options. - **preprocessing** (string) - Optional - Preprocessing method (e.g., "YAHOO"). - **frame_interval** (integer) - Optional - Interval in frames to process. - **aggregation_size** (integer) - Optional - Size of frames for aggregation. - **aggregation** (string) - Optional - Method for aggregation (e.g., "MEAN"). ### Request Example ```json { "input": { "type": "url", "data": "https://example.com/clip.mp4" }, "options": { "preprocessing": "YAHOO", "frame_interval": 8, "aggregation_size": 8, "aggregation": "MEAN" } } ``` ### Response #### Success Response (200) - **result** (object) - Contains the prediction results. - **elapsed_seconds** (array of numbers) - List of elapsed seconds for each frame. - **nsfw_probabilities** (array of numbers) - List of NSFW probabilities for each frame. - **processing_time_ms** (number) - The time taken for processing in milliseconds. - **version** (string) - The version of the library used. #### Response Example ```json { "result": { "elapsed_seconds": [0.0, 0.125, 0.25, ...], "nsfw_probabilities": [0.05, 0.07, 0.82, ...] }, "processing_time_ms": 8430.1, "version": "0.18.0" } ``` ``` -------------------------------- ### predict_video_frames Source: https://context7.com/bhky/opennsfw2/llms.txt Analyzes video frames for NSFW content, providing per-frame probabilities and optionally generating an annotated output video. ```APIDOC ## predict_video_frames ### Description Analyses every frame of a video and returns two parallel lists: elapsed time in seconds and NSFW probability per frame. Frames are sampled at configurable intervals and probabilities are aggregated over sliding windows to reduce noise. Optionally writes an annotated output MP4 with per-frame probability overlays. ### Parameters - **video_path** (str) - Path to the input video file. - **frame_interval** (int, optional) - Predict NSFW probability for every Nth frame. Defaults to 8. - **aggregation_size** (int, optional) - Number of frames to aggregate probabilities over in a sliding window. Defaults to 8. - **aggregation** (Aggregation, optional) - Method for aggregating probabilities (e.g., MEAN, MEDIAN, MAX, MIN). Defaults to `Aggregation.MEAN`. - **batch_size** (int, optional) - The number of frames to process in each batch. Defaults to 8. - **output_video_path** (str, optional) - Path to save the annotated output video with probability overlays. - **preprocessing** (Preprocessing, optional) - The preprocessing method to use. Defaults to `Preprocessing.YAHOO`. - **progress_bar** (bool, optional) - Whether to display a progress bar during processing. Defaults to True. ### Returns - **elapsed_secs** (list[float]) - List of elapsed times in seconds for each processed frame. - **nsfw_probs** (list[float]) - List of NSFW probabilities corresponding to each processed frame. ### Request Example ```python import opennsfw2 as n2 elapsed_secs, nsfw_probs = n2.predict_video_frames( video_path="clip.mp4", frame_interval=8, # predict every 8th frame aggregation_size=8, # aggregate over 8 frames per window aggregation=n2.Aggregation.MEAN, # MEAN | MEDIAN | MAX | MIN batch_size=8, output_video_path="clip_annotated.mp4", # optional annotated output preprocessing=n2.Preprocessing.YAHOO, progress_bar=True ) # Find the peak NSFW moment peak_idx = nsfw_probs.index(max(nsfw_probs)) print(f"Peak NSFW at {elapsed_secs[peak_idx]:.2f}s: {nsfw_probs[peak_idx]:.4f}") # Detect NSFW segments (probability >= 0.8) nsfw_segments = [ (elapsed_secs[i], nsfw_probs[i]) for i, p in enumerate(nsfw_probs) if p >= 0.8 ] print(f"NSFW segments: {nsfw_segments[:5]}") ``` ### Response Example ``` Peak NSFW at 15.20s: 0.9876 NSFW segments: [(15.20, 0.9876), (16.00, 0.8543), ...] ``` ```