Quick Start Guide #
Title

DeepID API Quick Start Guide for Deepfake Detection

Introduction

This guide provides a concise introduction to using the DeepID SDK for detecting deepfakes in various media formats such as images, videos, and audio files. Deepfake technology poses significant challenges by creating realistic yet counterfeit content; thus, utilizing tools like DeepID for verification has become crucial in many areas. This script illustrates the process of submitting media files to DeepID for analysis, retrieving the results, and saving them using Python.

Prerequisites

To successfully implement this guide, ensure you have the following:

  • Python 3.6+: A reliable version of Python installed on your machine.

  • DeepID SDK: A setup of the DeepID SDK on your development environment to facilitate interactions with the DeepID API.

  • DeepID API Key: A valid API key which allows access to DeepID's available detection services.

Description and Usage

Code Overview

This Python script serves the primary function of processing image, video, and audio files to detect deepfakes using the DeepID API. It outlines:

  1. Configuration: Set up using an API key in a production environment for leveraging the most robust models for deepfake detection.

  2. File Processing: Asynchronously submits files for analysis and polls for resultant data.

  3. Results Handling: Results are stored in a structured JSON format for easy access and validation.

Usage Instructions

  1. API Key Replacement: Replace the placeholder 'YOUR_API_KEY_HERE' within the script with your own valid DeepID API key to authenticate requests.

  2. File Paths Adjustment: Update the sample_files dictionary with the actual paths of the image, video, or audio files you intend to analyze.

  3. Execution: Run the script to process the files and obtain detection results.

Example Code

import time
import json
import os
from datetime import datetime
from deepid import API

# Configuration
API_KEY = ""
ENV = "production"  # Use 'production' for the most reliable models
MAX_RETRIES = 20
RETRY_DELAY = 5  # seconds
RESULTS_DIR = "deepid_results"

# Initialize the DeepID SDK
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
    ]
}

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}")
        return None

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']
        time.sleep(RETRY_DELAY)
    return None

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

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:
            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__":
    main()

By following these steps, users can effectively use the DeepID SDK to gain insights into the authenticity of media content, thus providing a toolset against the rise of deceptive deepfake media. If you have further questions or need additional modifications, feel free to ask!

Need some help?

© Deep Media AI
Documentation

V1.4