# Reality Defender SDK for Python
[](https://codecov.io/gh/Reality-Defender/realitydefender-sdk-python)
A Python SDK for the Reality Defender API to detect deepfakes and manipulated media.
## Installation
```bash
# 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](https://app.realitydefender.ai).
### Asynchronous Approach
This approach uses direct polling to wait for the analysis results.
```python
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.
```python
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
```python
rd = RealityDefender(
api_key="your-api-key", # Required: Your API key
)
```
### Upload Media for Analysis
```python
# 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
```python
# 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:
```python
{
"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)
}
]
}
```
### Event-Based Results
```python
# 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:
```python
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:
```bash
# 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.
Raw data
{
"_id": null,
"home_page": null,
"name": "realitydefender",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.10",
"maintainer_email": null,
"keywords": "deepfake, ai, detection, reality defender, media authentication, computer vision",
"author": "Reality Defender",
"author_email": "Reality Defender <support@realitydefender.com>",
"download_url": "https://files.pythonhosted.org/packages/f8/8f/c5a697ba87a33a16b188ffdcf7a49db66ad63a36c915d9ee3ff223fdd9b5/realitydefender-0.1.7.tar.gz",
"platform": null,
"description": "# Reality Defender SDK for Python\n\n[](https://codecov.io/gh/Reality-Defender/realitydefender-sdk-python)\n\nA Python SDK for the Reality Defender API to detect deepfakes and manipulated media.\n\n## Installation\n\n```bash\n# Using pip\npip install realitydefender\n\n# Using poetry\npoetry add realitydefender\n```\n\n## Getting Started\n\nFirst, you need to obtain an API key from the [Reality Defender Platform](https://app.realitydefender.ai).\n\n### Asynchronous Approach\n\nThis approach uses direct polling to wait for the analysis results.\n\n```python\nimport asyncio\nfrom realitydefender import RealityDefender\n\nasync def main():\n # Initialize the SDK with your API key\n print(\"Initializing Reality Defender SDK...\")\n rd = RealityDefender(api_key=\"your-api-key\")\n\n # Upload a file for analysis\n print(\"Uploading file for analysis...\")\n response = await rd.upload(file_path=\"/path/to/your/file.jpg\")\n request_id = response[\"request_id\"]\n print(f\"File uploaded successfully. Request ID: {request_id}\")\n\n # Get results by polling until completion\n print(\"Waiting for analysis results...\")\n result = await rd.get_result(request_id)\n print(\"Analysis complete!\")\n\n # Process the results\n print(\"\\nResults:\")\n print(f\"Status: {result['status']}\")\n print(f\"Score: {result['score']}\")\n\n # List model results\n print(\"\\nModel details:\")\n for model in result[\"models\"]:\n print(f\"{model['name']}: {model['status']} (Score: {model['score']})\")\n\n# Run the async function\nasyncio.run(main())\n```\n\n### Event-Based Approach\n\nThis approach uses event handlers to process results when they become available.\n\n```python\nimport asyncio\nfrom realitydefender import RealityDefender\n\nasync def main():\n # Initialize the SDK\n print(\"Initializing Reality Defender SDK...\")\n rd = RealityDefender(api_key=\"your-api-key\")\n\n # Set up event handlers\n print(\"Setting up event handlers...\")\n rd.on(\"result\", lambda result: print(f\"Result received: {result['status']} (Score: {result['score']})\"))\n rd.on(\"error\", lambda error: print(f\"Error occurred: {error.message}\"))\n\n # Upload and start polling\n print(\"Uploading file for analysis...\")\n response = await rd.upload(file_path=\"/path/to/your/file.jpg\")\n request_id = response[\"request_id\"]\n print(f\"File uploaded successfully. Request ID: {request_id}\")\n \n print(\"Starting to poll for results...\")\n await rd.poll_for_results(response[\"request_id\"])\n print(\"Polling complete!\")\n\n# Run the async function\nasyncio.run(main())\n```\n\n## Architecture\n\nThe SDK is designed with a modular architecture for better maintainability and testability:\n\n- **Client**: HTTP communication with the Reality Defender API\n- **Core**: Configuration, constants, and callbacks\n- **Detection**: Media upload and results processing\n- **Models**: Data classes for API responses and SDK interfaces\n- **Utils**: File operations and helper functions\n\n## API Reference\n\nThe Reality Defender SDK uses asynchronous operations throughout.\n\n### Initialize the SDK\n\n```python\nrd = RealityDefender(\n api_key=\"your-api-key\", # Required: Your API key\n)\n```\n\n### Upload Media for Analysis\n\n```python\n# Must be called from within an async function\nresponse = await rd.upload(file_path=\"/path/to/file.jpg\") # Required: Path to the file to analyze\n)\n```\n\nReturns: `{\"request_id\": str, \"media_id\": str}`\n\n### Get Results via Polling\n\n```python\n# Must be called from within an async function\n# This will poll until the analysis is complete\nresult = await rd.get_result(request_id)\n```\n\nReturns a dictionary with detection results:\n\n```python\n{\n \"status\": str, # Overall status (e.g., \"MANIPULATED\", \"AUTHENTIC\")\n \"score\": float, # Overall confidence score (0-1)\n \"models\": [ # Array of model-specific results\n {\n \"name\": str, # Model name\n \"status\": str, # Model-specific status\n \"score\": float # Model-specific score (0-1)\n }\n ]\n}\n```\n\n### Event-Based Results\n\n```python\n# Set up event handlers before polling\nrd.on(\"result\", callback_function) # Called when results are available\nrd.on(\"error\", error_callback_function) # Called if an error occurs\n\n# Start polling (must be called from within an async function)\nawait rd.poll_for_results(request_id)\n\n# Clean up when done (must be called from within an async function)\nawait rd.cleanup()\n```\n\n## Error Handling\n\nThe SDK raises exceptions for various error scenarios:\n\n```python\ntry:\n result = rd.upload(file_path=\"/path/to/file.jpg\")\nexcept RealityDefenderError as error:\n print(f\"Error: {error.message} ({error.code})\")\n # Error codes: 'unauthorized', 'server_error', 'timeout', \n # 'invalid_file', 'upload_failed', 'not_found', 'unknown_error'\n```\n\n## Examples\n\nSee the `examples` directory for more detailed usage examples.\n\n## Running Examples\n\nTo run the example code in this SDK, follow these steps:\n\n```bash\n# Navigate to the python directory\ncd python\n\n# Install the package in development mode\npip install -e .\n\n# Set your API key\nexport REALITY_DEFENDER_API_KEY='<your-api-key>'\n\n# Run the example\npython examples/basic_usage.py\n```\n\nThe example code demonstrates how to upload a sample image and process the detection results. ",
"bugtrack_url": null,
"license": null,
"summary": "SDK for the Reality Defender deepfake detection API",
"version": "0.1.7",
"project_urls": {
"Documentation": "https://github.com/Reality-Defender/eng-sdk/tree/main/python",
"Issue Tracker": "https://github.com/Reality-Defender/eng-sdk/issues",
"Source": "https://github.com/Reality-Defender/eng-sdk"
},
"split_keywords": [
"deepfake",
" ai",
" detection",
" reality defender",
" media authentication",
" computer vision"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "a97dc76fa208e5e6c7317a4aae2b14db0ee6c281e1d0437ef4db1272d6e9b75a",
"md5": "acf6931c5cf7e897d86061406a44535b",
"sha256": "10e7814bc3e4701351e4513c9b6dd9e0a80a8a21fad18b94a279eb28165b773d"
},
"downloads": -1,
"filename": "realitydefender-0.1.7-py3-none-any.whl",
"has_sig": false,
"md5_digest": "acf6931c5cf7e897d86061406a44535b",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.10",
"size": 20012,
"upload_time": "2025-07-18T02:53:01",
"upload_time_iso_8601": "2025-07-18T02:53:01.128495Z",
"url": "https://files.pythonhosted.org/packages/a9/7d/c76fa208e5e6c7317a4aae2b14db0ee6c281e1d0437ef4db1272d6e9b75a/realitydefender-0.1.7-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "f88fc5a697ba87a33a16b188ffdcf7a49db66ad63a36c915d9ee3ff223fdd9b5",
"md5": "5f81e964f9ec2d2daebd345e73fa0a74",
"sha256": "97b4bceb2696c1744fd9421acfd64752a08df8ff23f6cef0b1b124243909b611"
},
"downloads": -1,
"filename": "realitydefender-0.1.7.tar.gz",
"has_sig": false,
"md5_digest": "5f81e964f9ec2d2daebd345e73fa0a74",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.10",
"size": 14207,
"upload_time": "2025-07-18T02:53:01",
"upload_time_iso_8601": "2025-07-18T02:53:01.940833Z",
"url": "https://files.pythonhosted.org/packages/f8/8f/c5a697ba87a33a16b188ffdcf7a49db66ad63a36c915d9ee3ff223fdd9b5/realitydefender-0.1.7.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-07-18 02:53:01",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "Reality-Defender",
"github_project": "eng-sdk",
"github_not_found": true,
"lcname": "realitydefender"
}