Skip to main content

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")

    # 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']})")


# 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")

    # 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!")


# 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., "MANIPULATED", "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)
        }
    ]
}

DetectionResult includes heatmaps for IMAGE media when a non-ensemble model returns an artificial result (API status FAKE / UI ARTIFICIAL). Pre-signed URLs expire after 15 minutes; otherwise None:

result = await rd.get_result(request_id)

# IMAGE heatmaps: model slug → pre-signed PNG URL
print(result["heatmaps"])

Delete an analysis

Deletes a scan analysis (DELETE /api/media/{request_id}). The API responds with 204 No Content.

await rd.delete_analysis(request_id)

User feedback

# Must be called from within an async function
feedback = await rd.create_user_feedback(
    "your-request-id",
    "REAL",
    "CONFIRMATION",
    comment="Optional note",
)

Returns a UserFeedback dictionary (TypedDict). The create response includes the persisted feedback row; nullable enrichment fields may be None.

{
    "id": str,
    "userId": str,
    "requestId": str,
    "institutionId": str,
    "category": str,
    "label": str,
    "createdAt": str,
    "text": str | None,
    "userName": str | None,
    "userEmail": str | None,
    "orgName": str | None,
    "mediaType": str | None,
    "mediaViewUrl": str | None,
    "mediaSource": str | None,
}

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'

Supported file types and size limits

There is a size limit for each of the supported file types.

File Type Extensions Size Limit (bytes) Size Limit (MB)
Video .mp4, .mov 262,144,000 250 MB
Image .jpg, .png, .jpeg, .gif, .webp 52,428,800 50 MB
Audio .flac, .wav, .mp3, .m4a, .aac, .alac, .ogg 20,971,520 20 MB
Text .txt 5,242,880 5 MB

Supported social media platforms

The Reality Defender API supports analysis of media from the following social media platforms:

  • Facebook
  • Instagram
  • Twitter
  • YouTube
  • TikTok

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.

Metadata

Release files for realitydefender 0.1.14

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for realitydefender 0.1.14
File Size Uploaded Provenance Actions
realitydefender-0.1.14.tar.gz 19.0 kB Without provenance Details for realitydefender-0.1.14.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for realitydefender 0.1.14
File Interpreter ABI Platform Actions
realitydefender-0.1.14-py3-none-any.whl Python 3 none any Details for realitydefender-0.1.14-py3-none-any.whl

Total release size: 45.5 kB

Release files / realitydefender-0.1.14.tar.gz

Download URL realitydefender-0.1.14.tar.gz
Size 19.0 kB
Tags Source
SHA-256 checksum
How to use checksums
29d55ad07c1075c34f1204899aaa7b3b80383af23faf0965add6e0d26c78ffc4
BLAKE2b-256 checksum
How to use checksums
0bfac912fe24d10323b2e7a217facd97e6598e22e57817ab95692c22d68ddb43
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / realitydefender-0.1.14-py3-none-any.whl

Download URL realitydefender-0.1.14-py3-none-any.whl
Size 26.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
51b30e86e7edff74828d99e7ac39e86db02a63cde6e2016ceb91a42f70a4e79f
BLAKE2b-256 checksum
How to use checksums
803e88969c66b06e1fd5d38d37665be78057030b459bccb6764b2c80805503d6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for realitydefender 0.1.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page