DeepID SDK Quick Start Guide for Deepfake Detection

Table of Content
Table of Content
Title
Title
Title

DeepID SDK Quick Start Guide for Deepfake Detection

Introduction

This guide demonstrates how to use the DeepID SDK to detect deepfakes in images, videos, and audio files using Python. The DeepID API provides powerful tools for verifying the authenticity of media content.

Prerequisites

Before you begin, ensure you have:

  • Python 3.6 or later installed on your system

  • The DeepID SDK installed

  • A valid DeepID API key

If you haven't already, you can sign up for a DeepID API key here.

Set up your environment

First, let's set up your development environment to use the DeepID SDK.

  1. Install the DeepID SDK:

pip install deepid
  1. Set up your API key:

# Import the DeepID SDK and required package
import time
import json
import os, traceback
from datetime import datetime
from deepid import API
# Set your API key for authentication
deepid.api_key = 'YOUR_API_KEY_HERE'
# Consider using environment variables 
# or a secure configuration file in production

Replace 'YOUR_API_KEY_HERE' with the API key you received when signing up. It's crucial to keep this key secure and not share it publicly.

  1. Configure constants:

# Increase this if you're processing large files 
# or experiencing slow network connections
MAX_RETRIES = 10
ENV = "production"  # Use 'production' for the most reliable models
# Adjust this based on your expected processing time and API response time
RETRY_DELAY = 5

# Ensure this directory exists or has appropriate write permissions
RESULTS_DIR = 'results'


These constants control the behavior of our script:

  • MAX_RETRIES: The number of times to check for results before giving up.

  • RETRY_DELAY: The time (in seconds) to wait between result checks.

  • RESULTS_DIR: The directory where result files will be saved.

  1. Define your sample files:

#Initialize your DeepID Session
deepid = API(API_KEY, env=ENV)

# Sample files to process (replace with your own file paths)
sample_files = {
    "image": [
        # Add more image files here
    ],
    "video": [
        # Add video file paths here
    ],
    "audio": [
        # Add more audio files here
    ]
}

# Tip: For optimal performance,
# use high-quality uncompressed files when possible
# Larger files may take longer to process 
# but often yield more accurate results


Replace these placeholder paths with the actual paths to the files you want to analyze. You can add multiple files for each media type.

Make your first API request

Now that your environment is set up, let's make your first API request to analyze a file for deepfakes.

def process_file(file_path, modality):
    """Submit a file for processing using process_file_async."""
    try:
        response = deepid.process_file_async(
            file_path,
            run_description=False,
            modalities=[modality]
        )
        return response['id']
    except Exception as e:
        print(f"Error submitting file {file_path}: {e}"

Retrieve analysis results

After submitting a file, you need to poll for the results:

def get_results(file_id):
    """Poll for results of a processed file."""
    for _ in range(MAX_RETRIES):
        status_response = deepid.get_file_status(file_id)
        status = status_response['status']
        if status in ['PROCESSED', 'RESULTS']:
            return status_response['results'

This function checks the status of your analysis and retrieves the results when they're ready. It will retry up to MAX_RETRIES times, waiting RETRY_DELAY seconds between each attempt.

Save and manage results

Once you have the results, you'll want to save them for further analysis:

def save_results(file_path, results):
    """Save results to a JSON file."""
    if not os.path.exists(RESULTS_DIR):
        os.makedirs(RESULTS_DIR)
    
    filename = os.path.basename(file_path)
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    result_filename = f"{filename}_{timestamp}_result.json"
    result_path = os.path.join(RESULTS_DIR, result_filename)
    
    with open(result_path, 'w') as f:
        json.dump(results, f, indent=2)
    
    print(f"Results saved to: {result_path}"

This function saves the analysis results as a JSON file in the RESULTS_DIR directory, with a filename that includes the original filename and a timestamp.

Putting it all together

Now, let's use these functions to process all our sample files:

def process_files(file_list, modality):
    """Process files for a given modality."""
    print(f"\nProcessing {len(file_list)} {modality} files:")
    for file_path in file_list:
        try:
            print(f"Processing: {file_path}")
            file_id = process_file(file_path, modality)
            if file_id:
                print(f"File ID: {file_id}")
                results = get_results(file_id)
                if results:
                    print(f"Results for {file_path}: {results}")
                    save_results(file_path, results)
                else:
                    print(f"No results received for {file_path}")
            else:
                print(f"Failed to process {file_path}")
        except Exception as e:
            traceback.print_exc()
            print(f"Error processing {file_path}: {e}")

def main():
    """Main function to demonstrate processing for each media type."""
    for modality, file_list in sample_files.items():
        process_files(file_list, modality)

if __name__ == "__main__"

This main function processes each file in our sample_files dictionary, submits it for analysis, retrieves the results, and saves them.

Run the script

Execute the script with:

python your_script_name.py

You should see output indicating the progress of each file's analysis and where the results are saved.

Next Steps

Congratulations on making your first DeepID API request! You've taken the first step towards leveraging advanced deepfake detection in your projects. Here's how you can build on this foundation:

  1. Explore Advanced Features

    • Experiment with different modalities and detection settings to fine-tune your results.

    • Try processing various types of media (images, videos, audio) to understand the API's capabilities fully.

    • Explore the batch processing endpoint (/file/process/batch) for efficiently handling multiple files.

  2. Enhance Your Implementation

    • Implement robust error handling in your API calls to manage rate limits, network issues, and other potential problems.

    • Develop a logging system to track your API usage and monitor the performance of your deepfake detection processes.

    • Create scripts or a simple application to automate the entire process from upload to result analysis.

  3. Integrate and Innovate

    • Incorporate DeepID API results into your existing applications or workflows. For example, you could build a content moderation system that uses deepfake detection as part of its verification process.

    • Develop new tools or services based on deepfake detection capabilities, such as a browser extension that analyzes images and videos on social media platforms.

    • Combine DeepID's results with other AI services or datasets to create more comprehensive media analysis solutions.

Remember, the world of deepfake detection is rapidly evolving. By staying curious and continuing to experiment, you'll be at the forefront of this exciting technology. If you create something innovative with the DeepID API, we'd love to hear about it!

Happy coding, and welcome to the future of media authenticity!

© Deep Media AI
DeepID SDK Quick Start Guide for Deepfake Detection
DeepID SDK Quick Start Guide for Deepfake Detection
DeepID SDK Quick Start Guide for Deepfake Detection

Deep ID team

Deep ID team

Deep ID team

support@deepmedia.ai

support@deepmedia.ai

support@deepmedia.ai