Skip to main content

SDK for the Reality Defender deepfake detection API

Project description

Reality Defender SDK for Python

codecov

A Python SDK for the Reality Defender API to detect deepfakes and manipulated media.

Installation

# Using pip
pip install realitydefender

# Using poetry
poetry add realitydefender

Getting Started

First, you need to obtain an API key from the Reality Defender Platform.

Asynchronous Approach

This approach uses direct polling to wait for the analysis results.

import asyncio
from realitydefender import RealityDefender

async def main():
    # Initialize the SDK with your API key
    print("Initializing Reality Defender SDK...")
    rd = RealityDefender(api_key="your-api-key")

    try:
        # Upload a file for analysis
        print("Uploading file for analysis...")
        response = await rd.upload(file_path="/path/to/your/file.jpg")
        request_id = response["request_id"]
        print(f"File uploaded successfully. Request ID: {request_id}")

        # Get results by polling until completion
        print("Waiting for analysis results...")
        result = await rd.get_result(request_id)
        print("Analysis complete!")

        # Process the results
        print("\nResults:")
        print(f"Status: {result['status']}")
        print(f"Score: {result['score']}")

        # List model results
        print("\nModel details:")
        for model in result["models"]:
            print(f"{model['name']}: {model['status']} (Score: {model['score']})")
    finally:
        # Always clean up when done
        print("Cleaning up resources...")
        await rd.cleanup()
        print("Done!")

# Run the async function
asyncio.run(main())

Event-Based Approach

This approach uses event handlers to process results when they become available.

import asyncio
from realitydefender import RealityDefender

async def main():
    # Initialize the SDK
    print("Initializing Reality Defender SDK...")
    rd = RealityDefender(api_key="your-api-key")

    try:
        # Set up event handlers
        print("Setting up event handlers...")
        rd.on("result", lambda result: print(f"Result received: {result['status']} (Score: {result['score']})"))
        rd.on("error", lambda error: print(f"Error occurred: {error.message}"))

        # Upload and start polling
        print("Uploading file for analysis...")
        response = await rd.upload(file_path="/path/to/your/file.jpg")
        request_id = response["request_id"]
        print(f"File uploaded successfully. Request ID: {request_id}")
        
        print("Starting to poll for results...")
        await rd.poll_for_results(response["request_id"])
        print("Polling complete!")
    finally:
        # Clean up when done
        print("Cleaning up resources...")
        await rd.cleanup()
        print("Done!")

# Run the async function
asyncio.run(main())

Architecture

The SDK is designed with a modular architecture for better maintainability and testability:

  • Client: HTTP communication with the Reality Defender API
  • Core: Configuration, constants, and callbacks
  • Detection: Media upload and results processing
  • Models: Data classes for API responses and SDK interfaces
  • Utils: File operations and helper functions

API Reference

The Reality Defender SDK uses asynchronous operations throughout.

Initialize the SDK

rd = RealityDefender(
    api_key="your-api-key",               # Required: Your API key
)

Upload Media for Analysis

# Must be called from within an async function
response = await rd.upload(file_path="/path/to/file.jpg")     # Required: Path to the file to analyze
)

Returns: {"request_id": str, "media_id": str}

Get Results via Polling

# Must be called from within an async function
# This will poll until the analysis is complete
result = await rd.get_result(request_id)

Returns a dictionary with detection results:

{
    "status": str,       # Overall status (e.g., "ARTIFICIAL", "AUTHENTIC")
    "score": float,      # Overall confidence score (0-1)
    "models": [          # Array of model-specific results
        {
            "name": str,     # Model name
            "status": str,   # Model-specific status
            "score": float   # Model-specific score (0-1)
        }
    ]
}

Event-Based Results

# Set up event handlers before polling
rd.on("result", callback_function)  # Called when results are available
rd.on("error", error_callback_function)  # Called if an error occurs

# Start polling (must be called from within an async function)
await rd.poll_for_results(request_id)

# Clean up when done (must be called from within an async function)
await rd.cleanup()

Error Handling

The SDK raises exceptions for various error scenarios:

try:
    result = rd.upload(file_path="/path/to/file.jpg")
except RealityDefenderError as error:
    print(f"Error: {error.message} ({error.code})")
    # Error codes: 'unauthorized', 'server_error', 'timeout', 
    # 'invalid_file', 'upload_failed', 'not_found', 'unknown_error'

Examples

See the examples directory for more detailed usage examples.

Running Examples

To run the example code in this SDK, follow these steps:

# Navigate to the python directory
cd python

# Install the package in development mode
pip install -e .

# Set your API key
export REALITY_DEFENDER_API_KEY='<your-api-key>'

# Run the example
python examples/basic_usage.py

The example code demonstrates how to upload a sample image and process the detection results.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

realitydefender-0.1.3.tar.gz (12.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

realitydefender-0.1.3-py3-none-any.whl (17.7 kB view details)

Uploaded Python 3

File details

Details for the file realitydefender-0.1.3.tar.gz.

File metadata

  • Download URL: realitydefender-0.1.3.tar.gz
  • Upload date:
  • Size: 12.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.15

File hashes

Hashes for realitydefender-0.1.3.tar.gz
Algorithm Hash digest
SHA256 165d8cf02f3dd979312dca64228ee24a3bc512baf76625381f35cf14aecf02fb
MD5 70df267ca4001af2a0f46311b9d7f742
BLAKE2b-256 e64b7c9706a14af54aad80e2477e18a652a539f6fe39b5c4e214415017e98693

See more details on using hashes here.

File details

Details for the file realitydefender-0.1.3-py3-none-any.whl.

File metadata

File hashes

Hashes for realitydefender-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 db628bd34035393e187faee3c38bc634de4c0cb57deb66cfdb745ff2b9b47dce
MD5 14c79c9c38b3b141c72942dd0e4f34c4
BLAKE2b-256 39dddaf76e9e0b57d5b9b06410e805b6ddb075ebdcd331fe51da9efae28addea

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page