Image Moderation Examples

Examples of how to moderate image content using the Omni API

Basic Image Moderation

This example shows how to moderate a single image. The image must be base64-encoded and include the appropriate MIME type prefix.

Request

curl -X POST https://api.omnimoderate.com/v1/moderate \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your_api_key_here" \
  -d '{
    "input": [
      { "type": "image", "base64": "data:image/jpeg;base64,/9j/4AAQSkZ..." }
    ]
  }'

Response

{
  "id": "modr-123459",
  "model": "text-moderation-latest",
  "results": [
    {
      "flagged": false,
      "categories": {
        "hate": false,
        "harassment": false,
        "self-harm": false,
        "sexual": false,
        "violence": false
      },
      "category_scores": {
        "hate": 0.0,
        "harassment": 0.0,
        "self-harm": 0.0,
        "sexual": 0.0,
        "violence": 0.0
      }
    }
  ],
  "flagged": false,
  "signature": "abcdef1234567893"
}

Image Moderation with Vision Analysis

This example shows how to moderate an image with additional vision analysis. The analyze_images parameter is set to true to enable vision analysis.

Request

curl -X POST https://api.omnimoderate.com/v1/moderate \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your_api_key_here" \
  -d '{
    "input": [
      { "type": "image", "base64": "data:image/jpeg;base64,/9j/4AAQSkZ..." }
    ],
    "analyze_images": true
  }'

Response

{
  "id": "modr-123460",
  "model": "text-moderation-latest",
  "results": [
    {
      "flagged": false,
      "categories": {
        "hate": false,
        "harassment": false,
        "self-harm": false,
        "sexual": false,
        "violence": false
      },
      "category_scores": {
        "hate": 0.0,
        "harassment": 0.0,
        "self-harm": 0.0,
        "sexual": 0.0,
        "violence": 0.0
      }
    }
  ],
  "vision_analysis": [
    {
      "image_index": 0,
      "analysis": "This image shows a plate of beautifully presented food in what appears to be a restaurant setting. The dish looks like a well-plated steak with garnishes and side dishes. The lighting is good, the food appears appetizing, and the image is of high quality. This is perfectly appropriate for a restaurant listing or review as it showcases the food offerings. VERDICT: APPROPRIATE",
      "flagged": false
    }
  ],
  "flagged": false,
  "signature": "abcdef1234567894"
}

Multiple Images

This example shows how to moderate multiple images in a single request:

Request

curl -X POST https://api.omnimoderate.com/v1/moderate \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your_api_key_here" \
  -d '{
    "input": [
      { "type": "image", "base64": "data:image/jpeg;base64,/9j/4AAQSkZ..." },
      { "type": "image", "base64": "data:image/jpeg;base64,iVBORw0KGg..." }
    ],
    "analyze_images": true
  }'

Response

{
  "id": "modr-123461",
  "model": "text-moderation-latest",
  "results": [
    {
      "flagged": false,
      "categories": {
        "hate": false,
        "harassment": false,
        "self-harm": false,
        "sexual": false,
        "violence": false
      },
      "category_scores": {
        "hate": 0.0,
        "harassment": 0.0,
        "self-harm": 0.0,
        "sexual": 0.0,
        "violence": 0.0
      }
    },
    {
      "flagged": false,
      "categories": {
        "hate": false,
        "harassment": false,
        "self-harm": false,
        "sexual": false,
        "violence": false
      },
      "category_scores": {
        "hate": 0.0,
        "harassment": 0.0,
        "self-harm": 0.0,
        "sexual": 0.0,
        "violence": 0.0
      }
    }
  ],
  "vision_analysis": [
    {
      "image_index": 0,
      "analysis": "This image shows a plate of beautifully presented food in what appears to be a restaurant setting. The dish looks like a well-plated steak with garnishes and side dishes. The lighting is good, the food appears appetizing, and the image is of high quality. This is perfectly appropriate for a restaurant listing or review as it showcases the food offerings. VERDICT: APPROPRIATE",
      "flagged": false
    },
    {
      "image_index": 1,
      "analysis": "This image shows the interior of a restaurant with tables and chairs. The space appears clean, well-lit, and professionally designed. This is an appropriate image for a restaurant listing as it accurately represents the dining environment for potential customers. There are no inappropriate elements or overlays in the image. VERDICT: APPROPRIATE",
      "flagged": false
    }
  ],
  "flagged": false,
  "signature": "abcdef1234567895"
}

Code Examples

JavaScript

moderate-image.js
// Function to convert an image file to base64
function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

async function moderateImages(apiKey, imageFiles, analyzeImages = false) {
  // Convert all image files to base64
  const base64Promises = imageFiles.map(file => fileToBase64(file));
  const base64Images = await Promise.all(base64Promises);
  
  const response = await fetch('https://api.omnimoderate.com/v1/moderate', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': apiKey
    },
    body: JSON.stringify({
      input: base64Images.map(base64 => ({ type: 'image', base64 })),
      analyze_images: analyzeImages
    })
  });

  if (!response.ok) {
    const errorData = await response.json();
    throw new Error(errorData.error?.message || 'Moderation request failed');
  }

  return await response.json();
}

// Example usage with file input
document.getElementById('imageForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  
  const apiKey = 'your_api_key_here';
  const fileInput = document.getElementById('imageInput');
  const analyzeImages = document.getElementById('analyzeImages').checked;
  
  try {
    const result = await moderateImages(apiKey, Array.from(fileInput.files), analyzeImages);
    
    console.log('Moderation result:', result);
    console.log('Flagged:', result.flagged);
    
    if (analyzeImages && result.vision_analysis) {
      result.vision_analysis.forEach((analysis, index) => {
        console.log(`Image ${index + 1} analysis: ${analysis.analysis}`);
        console.log(`Image ${index + 1} flagged: ${analysis.flagged}`);
      });
    }
  } catch (error) {
    console.error('Error:', error.message);
  }
});

Python

moderate_image.py
import requests
import base64
from pathlib import Path

def encode_image_to_base64(image_path):
    """Convert an image file to base64 encoding with MIME type prefix"""
    image_path = Path(image_path)
    mime_type = f"image/{image_path.suffix[1:]}"  # Remove the dot from extension
    
    with open(image_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
        return f"data:{mime_type};base64,{encoded_string}"

def moderate_images(api_key, image_paths, analyze_images=False):
    """Moderate multiple images using the Omni API"""
    url = "https://api.omnimoderate.com/v1/moderate"
    
    headers = {
        "Content-Type": "application/json",
        "X-API-Key": api_key
    }
    
    # Convert all images to base64
    base64_images = [encode_image_to_base64(path) for path in image_paths]
    
    payload = {
        "input": [{"type": "image", "base64": base64} for base64 in base64_images],
        "analyze_images": analyze_images
    }
    
    response = requests.post(url, headers=headers, json=payload)
    
    if response.status_code != 200:
        error_data = response.json()
        raise Exception(error_data.get("error", {}).get("message", "Moderation request failed"))
    
    return response.json()

# Example usage
def example():
    api_key = "your_api_key_here"
    image_paths = ["path/to/image1.jpg", "path/to/image2.png"]
    
    try:
        # Moderate images with vision analysis
        result = moderate_images(api_key, image_paths, analyze_images=True)
        
        print(f"Moderation result: {result['flagged']}")
        
        # Check individual results
        for i, result_item in enumerate(result['results']):
            print(f"Image {i + 1} flagged: {result_item['flagged']}")
        
        # Check vision analysis
        if 'vision_analysis' in result:
            for analysis in result['vision_analysis']:
                print(f"Image {analysis['image_index'] + 1} analysis: {analysis['analysis']}")
                print(f"Image {analysis['image_index'] + 1} flagged: {analysis['flagged']}")
    
    except Exception as e:
        print(f"Error: {str(e)}")

if __name__ == "__main__":
    example()

Next Steps