Table of Content
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 deepid
import os
import json
from datetime import datetime
# 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

# 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:

# Dictionary of sample files to be processed, organized by media type
sample_files = {
    # List of image files to analyze
    "image": ["path/to/image1.jpg", "path/to/image2.png"],

    # List of video files to analyze
    "video": ["path/to/video1.mp4"],

    # List of audio files to analyze
    "audio": ["path/to/audio1.wav"]
}

# 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 asynchronous processing by the DeepID API.
    """
    try:
        # Call the DeepID API to process the file asynchronously
        response = deepid.process_file_async(
            file_path,
            run_description=False,  
            # Set to True if you want a detailed description of the analysis
            modalities=[modality]  
            # Specify the type of media being analyzed
        )
        
        # Return the job ID, which will be used to retrieve results later
        return response['id']
    
    except Exception as e:
        # If an error occurs during submission, print the error and return None
        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):
    """
    Retrieve the results of a processed file from the DeepID API.    """
    # Attempt to retrieve results up to MAX_RETRIES times
    for _ in range(MAX_RETRIES):
        # Check the status of the submitted job
        status_response = deepid.get_file_status(file_id)
        
        # If the file has been processed or results are ready, return them
        if status_response['status'] in ['PROCESSED', 'RESULTS']:
            return status_response['results']
        
        # If results are not ready, 
        # wait for RETRY_DELAY seconds before checking again
        time.sleep(RETRY_DELAY)
    
    # If results are not available after MAX_RETRIES, return None

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 the analysis results to a JSON file.
    """
    # Create the results directory if it doesn't exist
    if not os.path.exists(RESULTS_DIR):
        os.makedirs(RESULTS_DIR)

    # Extract the filename from the original file path
    filename = os.path.basename(file_path)
    
    # Generate a timestamp for unique file naming
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    
    # Create a new filename for the results, 
    # including the original filename and timestamp
    result_filename = f"{filename}_{timestamp}_result.json"
    
    # Combine the results directory path with the new filename
    result_path = os.path.join(RESULTS_DIR, result_filename)

    # Write the results to a JSON file
    with open(result_path, 'w') as f:
        # Use indent=2 for pretty-printing the JSON for better readability
        json.dump(results, f, indent=2)

    # Print a confirmation message with the path to the saved results
    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 main():
    """
    Main function to process all files in the sample_files dictionary.
    """
    # Iterate through each modality (image, video, audio) and its file list
    for modality, file_list in sample_files.items():
        print(f"\nProcessing {len(file_list)} {modality} files:")
        
        # Process each file in the current modality
        for file_path in file_list:
            print(f"Processing: {file_path}")
            
            # Submit the file for processing
            file_id = process_file(file_path, modality)
            
            if file_id:
                # If file submission was successful, retrieve the results
                results = get_results(file_id)
                
                if results:
                    # If results were retrieved successfully, 
                    # print and save them
                    print(f"Results for {file_path}: {results}")
                    save_results(file_path, results)
                else:
                    # If no results were retrieved, print an error message
                    print(f"No results received for {file_path}")
            else:
                # If file submission failed, print an error message
                print(f"Failed to process {file_path}")

# Check if this script is being run directly (not imported as a module)
if __name__ == "__main__":
    # Execute the main function

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

Deep ID team

support@deepmedia.ai