Skip to main content

Build Your First Detection Script

ยท 7 min read
Sagar Pingale
Software Engineer at Deepfaic

Welcome to your first hands-on tutorial with the Deepfaic API! In this post, we'll build a simple yet powerful Python script that can analyze any media file for deepfake content. By the end of this tutorial, you'll have a working command-line tool that uploads files, creates analysis jobs, and retrieves results - all with just a single command.

What We're Buildingโ€‹

We're going to create a Python script that can:

  1. ๐Ÿ“ค Upload your file to Deepfaic
  2. ๐Ÿš€ Create an analysis job
  3. โฑ๏ธ Monitor the job status every 2 seconds
  4. ๐Ÿ“Š Display the results when complete

All with just running

python deepfaic.py /path/to/your/video.mp4

Prerequisitesโ€‹

Before we start coding, make sure you have:

  • Python 3.7 or higher installed
  • A Deepfaic API key (contact our team if you don't have one)
  • The requests library (pip install requests)

The Complete Scriptโ€‹

Let's dive right into the code! Here's our complete deepfaic.py script:

"""
Deepfaic API Tutorial Script
A simple command-line tool for deepfake detection using the Deepfaic API.

Usage: python deepfaic.py <filepath>
"""

import requests
import time
import sys
import os
from typing import Dict, Any

# Configuration
API_BASE_URL = "https://api.deepfaic.com/v1"
API_KEY = "your_key_here" # Replace with your actual API key

class DeepfaicClient:
def __init__(self, api_key: str):
self.api_key = api_key
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
self.session = requests.Session()
self.session.headers.update(self.headers)

def upload_file(self, file_path: str) -> str:
"""Upload a file to Deepfaic and return the file ID."""
print(f"๐Ÿ“ค Uploading file: {os.path.basename(file_path)}")

# Prepare file upload - note: don't include Content-Type for multipart
upload_headers = {"Authorization": f"Bearer {self.api_key}"}

with open(file_path, 'rb') as file:
files = {'file': (os.path.basename(file_path), file)}
response = requests.post(
f"{API_BASE_URL}/file/upload",
headers=upload_headers,
files=files
)

if response.status_code != 200:
raise Exception(f"File upload failed: {response.text}")

result = response.json()
file_id = result['data']['id']
print(f"โœ… File uploaded successfully! File ID: {file_id}")
return file_id

def create_job(self, file_id: str) -> int:
"""Create a deepfake analysis job and return the job ID."""
print(f"๐Ÿš€ Creating analysis job for file ID: {file_id}")

job_data = {
"file_id": file_id,
"title": f"API Tutorial Analysis - {time.strftime('%Y-%m-%d %H:%M:%S')}"
}

response = self.session.post(f"{API_BASE_URL}/job/create", json=job_data)

if response.status_code != 200:
raise Exception(f"Job creation failed: {response.text}")

result = response.json()
job_data_response = result['data']

# Extract the actual job ID from the response
if isinstance(job_data_response, dict) and 'job_id' in job_data_response:
job_id = job_data_response['job_id']
else:
job_id = job_data_response

print(f"โœ… Job created successfully! Job ID: {job_id}")
return job_id

def get_job_status(self, job_id: int) -> Dict[str, Any]:
"""Get the current status and results of a job."""
response = self.session.get(f"{API_BASE_URL}/job/get/full?job_id={job_id}")

if response.status_code != 200:
raise Exception(f"Failed to get job status: {response.text}")

result = response.json()
return result['data'][0] if result['data'] else None

def wait_for_completion(self, job_id: int) -> Dict[str, Any]:
"""Wait for job completion and return the final results."""
print(f"โฑ๏ธ Monitoring job {job_id} for completion...")

while True:
job_data = self.get_job_status(job_id)

if not job_data:
raise Exception("Job not found")

status = job_data['job']['status']
print(f"๐Ÿ“Š Current status: {status}")

if status == 'complete':
print("๐ŸŽ‰ Analysis completed!")
return job_data
elif 'error' in status.lower():
raise Exception(f"Job failed with status: {status}")

# Wait 2 seconds before checking again
time.sleep(2)

def display_results(self, job_data: Dict[str, Any]):
"""Display the analysis results in a user-friendly format."""
print("\n" + "="*60)
print("๐Ÿ” DEEPFAKE ANALYSIS RESULTS")
print("="*60)

job_info = job_data['job']
print(f"๐Ÿ“ File: {job_info['file_name']}")
print(f"๐Ÿ“… Analyzed: {job_info['created_at']}")
print(f"โฑ๏ธ Duration: {job_info.get('length', 'N/A')}")
print(f"๐Ÿ“ Type: {job_info['file_type']}")

print("\n๐Ÿค– AI Model Results:")
print("-" * 40)

# Video Model Results (Visual Analysis)
video = job_data.get('video')
if video and video.get('status') == 'complete':
score = video.get('score')
if score is not None:
# Score is between 0-1, convert to percentage for display
score_percent = score * 100
confidence = "HIGH" if score >= 0.6 else "MEDIUM" if score > 0.5 else "LOW"
print(f"๐ŸŽฅ Video Analysis: {score_percent:.1f}% | {confidence} CONFIDENCE")
if score >= 0.6:
print(" โš ๏ธ High probability of visual deepfake detected!")
else:
print(" โœ… Video appears authentic")
else:
print("๐ŸŽฅ Video: Analysis completed with no detections")

# Audio Model Results
audio = job_data.get('audio')
if audio and audio.get('status') == 'complete':
score = audio.get('score')
if score is not None:
# Score is between 0-1, convert to percentage for display
score_percent = score * 100
confidence = "HIGH" if score >= 0.6 else "MEDIUM" if score > 0.5 else "LOW"
print(f"๏ฟฝ๏ธ Audio Analysis: {score_percent:.1f}% | {confidence} CONFIDENCE")
if score >= 0.6:
print(" โš ๏ธ High probability of synthetic audio detected!")
else:
print(" โœ… Audio appears authentic")
else:
print("๐ŸŽ™๏ธ Audio: Analysis completed with no detections")

print("\n" + "="*60)

# Overall assessment
all_scores = [s for s in [video.get('score') if video else None,
audio.get('score') if audio else None] if s is not None]
if all_scores:
avg_score = sum(all_scores) / len(all_scores)
if avg_score >= 0.6:
print("๐Ÿšจ VERDICT: HIGH RISK - Potential deepfake detected!")
elif avg_score > 0.4:
print("โš ๏ธ VERDICT: MEDIUM RISK - Manual review recommended")
else:
print("โœ… VERDICT: LOW RISK - Content appears authentic")

print("="*60)

def main():
"""Main function to run the deepfake detection script."""

# Check command line arguments
if len(sys.argv) != 2:
print("โŒ Usage: python deepfaic.py <filepath>")
print("๐Ÿ“ Example: python deepfaic.py ./video.mp4")
sys.exit(1)

file_path = sys.argv[1]

# Validate file exists
if not os.path.exists(file_path):
print(f"โŒ Error: File '{file_path}' not found!")
sys.exit(1)

try:
print("๐Ÿš€ Starting Deepfaic Analysis...")
print(f"๐Ÿ“ Target file: {file_path}")

# Initialize client
client = DeepfaicClient(API_KEY)

# Step 1: Upload file
file_id = client.upload_file(file_path)

# Step 2: Create job
job_id = client.create_job(file_id)

# Step 3: Wait for completion
job_data = client.wait_for_completion(job_id)

# Step 4: Display results
client.display_results(job_data)

except KeyboardInterrupt:
print("\nโน๏ธ Analysis interrupted by user")
sys.exit(0)
except Exception as e:
print(f"\nโŒ Error: {str(e)}")
sys.exit(1)

if __name__ == "__main__":
main()

How to Use the Scriptโ€‹

Step 1: Setupโ€‹

  1. Save the script as deepfaic.py
  2. Replace "your-api-key-here" with your actual Deepfaic API key
  3. Make sure you have the requests library installed:
    pip install requests

Step 2: Run the Scriptโ€‹

Navigate to the directory containing your script and run:

python deepfaic.py /path/to/your/media/file.mp4

Step 3: Watch the Magic Happen!โ€‹

The script will show you real-time progress:

๐Ÿš€ Starting Deepfaic Analysis...
๐Ÿ“ Target file: /path/to/video.mp4
๐Ÿ“ค Uploading file: video.mp4
โœ… File uploaded successfully! File ID: abc-123-def
๐Ÿš€ Creating analysis job for file ID: abc-123-def
โœ… Job created successfully! Job ID: 42
โฑ๏ธ Monitoring job 42 for completion...
๐Ÿ“Š Current status: processing
๐Ÿ“Š Current status: processing
๐Ÿ“Š Current status: completed
๐ŸŽ‰ Analysis completed!

Your results are automatically available over at App Dashboard, make sure to check them out!

Understanding the Resultsโ€‹

The script provides detailed analysis across two AI models:

Video Modelโ€‹

  • What it does: Analyzes visual content for deepfake manipulation and AI-generated imagery
  • Best for: Videos, images, detecting facial manipulations and synthetic visual content
  • Output: Provides frame-by-frame analysis with detection scores

Audio Modelโ€‹

  • What it does: Identifies synthetic or cloned voices in audio content
  • Best for: Videos with spoken content, audio files, voice verification
  • Output: Provides chunk-based analysis of audio segments

Conclusionโ€‹

Congratulations! ๐ŸŽ‰ You've just built your first deepfake detection tool using the Deepfaic API. This script demonstrates the power and simplicity of integrating AI-powered media verification into your applications.

The Deepfaic API makes it incredibly easy to add enterprise-grade deepfake detection to any project. Whether you're building content moderation systems, security applications, or media verification tools, you now have the foundation to get started.

Happy coding, and stay safe in the digital world! ๐Ÿš€


Have questions or need help? Reach out to our support team at support@deepfaic.com