Introduction
Python has become the go-to language for AI and machine learning work, and deepfake detection is no exception. Whether you're a security researcher, content moderator, or developer building verification tools, Python provides the flexibility and powerful libraries you need to detect synthetic media at scale.
This comprehensive tutorial walks you through four practical methods for detecting deepfakes using Python, from a simple API call to building a complete batch processing pipeline and real-time webcam application. Each approach is production-ready and includes full, runnable code examples.
By the end of this guide, you'll understand how to integrate deepfake detection into your applications, process multiple images efficiently, build web interfaces, and monitor video feeds in real time.
Prerequisites
Before you start, make sure you have:
- Python 3.8 or higher installed on your machine
- Basic familiarity with Python and command line tools
- The
requestslibrary for making HTTP calls - An API key from deepfakedetectionapi.ai (free tier available)
Install the requests library using pip:
pip install requests
To get your free API key, visit our quickstart guide and sign up. You'll receive your key instantly.
Method 1: Using the Deepfake Detection API (Simplest)
The easiest way to get started with deepfake detection is to use our REST API directly. This method requires just a few lines of Python and works for any image hosted online or uploaded as base64.
Install and Import
import requests
import json
import base64
from pathlib import Path
# Your API key
API_KEY = "your-api-key-here"
API_URL = "https://api.deepfakedetectionapi.ai/v1/detect"
Basic Detection Script
def detect_deepfake(image_path):
"""
Detect if an image is a deepfake.
Supports both local files and URLs.
"""
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
# Check if input is a URL or local file
if image_path.startswith("http"):
# Use URL directly
payload = {"image_url": image_path}
else:
# Read local file and encode as base64
with open(image_path, "rb") as f:
image_data = base64.b64encode(f.read()).decode("utf-8")
payload = {"image_base64": image_data}
# Make the API request
response = requests.post(API_URL, json=payload, headers=headers, timeout=30)
if response.status_code == 200:
result = response.json()
return result
else:
raise Exception(f"API error: {response.status_code} {response.text}")
# Example usage
if __name__ == "__main__":
result = detect_deepfake("path/to/image.jpg")
print(f"Is Deepfake: {result['is_deepfake']}")
print(f"Confidence: {result['confidence']:.2%}")
print(f"Model: {result['model_version']}")
Understanding the Response
The API returns a JSON response with the following structure:
{
"is_deepfake": false,
"confidence": 0.94,
"model_version": "v3.2",
"processing_time_ms": 245,
"face_count": 1
}
- is_deepfake: Boolean indicating if the image is synthetic (true) or likely real (false)
- confidence: Decimal between 0 and 1 representing confidence in the prediction
- model_version: Version of the detection model used
- processing_time_ms: Time taken to analyze the image
- face_count: Number of faces detected in the image
Error Handling and Retries
import time
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def create_session_with_retries():
"""Create a requests session with automatic retry logic."""
session = requests.Session()
retry_strategy = Retry(
total=3,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504]
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
def detect_deepfake_robust(image_path, max_retries=3):
"""Detect deepfakes with robust error handling."""
session = create_session_with_retries()
headers = {"Authorization": f"Bearer {API_KEY}"}
for attempt in range(max_retries):
try:
if image_path.startswith("http"):
payload = {"image_url": image_path}
else:
with open(image_path, "rb") as f:
image_data = base64.b64encode(f.read()).decode()
payload = {"image_base64": image_data}
response = session.post(
API_URL,
json=payload,
headers=headers,
timeout=30
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
if attempt < max_retries - 1:
wait_time = 2 ** attempt
print(f"Attempt {attempt + 1} failed, retrying in {wait_time}s...")
time.sleep(wait_time)
else:
raise Exception(f"Failed after {max_retries} attempts: {e}")
Method 2: Batch Processing Multiple Images
When you need to analyze hundreds or thousands of images, sequential processing becomes slow. This method uses Python's concurrent.futures to process multiple images in parallel and save results to CSV.
import csv
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import requests
import base64
from datetime import datetime
def process_single_image(image_path, api_key, api_url):
"""Process a single image and return results."""
try:
headers = {"Authorization": f"Bearer {api_key}"}
with open(image_path, "rb") as f:
image_data = base64.b64encode(f.read()).decode()
payload = {"image_base64": image_data}
response = requests.post(api_url, json=payload, headers=headers, timeout=30)
if response.status_code == 200:
result = response.json()
return {
"file": Path(image_path).name,
"path": image_path,
"is_deepfake": result["is_deepfake"],
"confidence": result["confidence"],
"model": result["model_version"],
"status": "success"
}
else:
return {
"file": Path(image_path).name,
"path": image_path,
"status": "error",
"error": response.status_code
}
except Exception as e:
return {
"file": Path(image_path).name,
"path": image_path,
"status": "error",
"error": str(e)
}
def batch_process_directory(directory, api_key, output_csv=None, max_workers=5):
"""
Process all images in a directory and save results to CSV.
"""
api_url = "https://api.deepfakedetectionapi.ai/v1/detect"
# Find all image files
image_extensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp"}
image_files = []
for ext in image_extensions:
image_files.extend(Path(directory).glob(f"*{ext}"))
image_files.extend(Path(directory).glob(f"*{ext.upper()}"))
if not image_files:
print(f"No images found in {directory}")
return []
print(f"Found {len(image_files)} images. Processing...")
results = []
processed = 0
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {
executor.submit(process_single_image, str(img), api_key, api_url): img
for img in image_files
}
for future in as_completed(futures):
result = future.result()
results.append(result)
processed += 1
# Progress reporting
status = result.get("status", "unknown")
deepfake = result.get("is_deepfake", "N/A")
confidence = result.get("confidence", 0)
print(f"[{processed}/{len(image_files)}] {result['file']}: {status}", end="")
if status == "success":
print(f" - Deepfake: {deepfake} ({confidence:.1%})")
else:
print(f" - {result.get('error', 'Unknown error')}")
# Save results to CSV
if output_csv:
with open(output_csv, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=results[0].keys())
writer.writeheader()
writer.writerows(results)
print(f"Results saved to {output_csv}")
return results
# Example usage
if __name__ == "__main__":
results = batch_process_directory(
"./images",
api_key=API_KEY,
output_csv="deepfake_results.csv",
max_workers=5
)
This script processes up to 5 images concurrently, reports progress, and saves results to a CSV file with columns for filename, deepfake status, confidence score, and any errors encountered.
Method 3: Building a Simple Web App with Flask
Flask makes it easy to build a web interface for deepfake detection. Users can upload images via a web form and get instant results.
from flask import Flask, render_template, request, jsonify
import requests
import base64
import os
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024 # 16MB max
app.config["UPLOAD_FOLDER"] = "uploads"
API_KEY = os.getenv("DEEPFAKE_API_KEY")
API_URL = "https://api.deepfakedetectionapi.ai/v1/detect"
@app.route("/")
def index():
return render_template("index.html")
@app.route("/api/detect", methods=["POST"])
def detect_endpoint():
if "file" not in request.files:
return jsonify({"error": "No file provided"}), 400
file = request.files["file"]
if file.filename == "":
return jsonify({"error": "No file selected"}), 400
try:
# Read file and encode as base64
image_data = base64.b64encode(file.read()).decode()
# Call API
headers = {"Authorization": f"Bearer {API_KEY}"}
payload = {"image_base64": image_data}
response = requests.post(API_URL, json=payload, headers=headers, timeout=30)
if response.status_code == 200:
return jsonify(response.json()), 200
else:
return jsonify({"error": "API error"}), 500
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == "__main__":
os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True)
app.run(debug=True, port=5000)
HTML template for the web interface:
<!DOCTYPE html>
<html>
<head>
<title>Deepfake Detector</title>
<style>
body { font-family: Arial; max-width: 600px; margin: 50px auto; }
.result { padding: 20px; background: #f0f0f0; border-radius: 8px; }
.deepfake { background: #ffe0e0; }
.real { background: #e0ffe0; }
</style>
</head>
<body>
<h1>Deepfake Detector</h1>
<form id="uploadForm">
<input type="file" id="imageFile" accept="image/*" required>
<button type="submit">Analyze</button>
</form>
<div id="result"></div>
<script>
document.getElementById("uploadForm").addEventListener("submit", async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append("file", document.getElementById("imageFile").files[0]);
const response = await fetch("/api/detect", { method: "POST", body: formData });
const data = await response.json();
const resultDiv = document.getElementById("result");
const deepfakeClass = data.is_deepfake ? "deepfake" : "real";
resultDiv.innerHTML = `<div class="result ${deepfakeClass}"><p>Deepfake: ${data.is_deepfake}</p><p>Confidence: ${(data.confidence * 100).toFixed(1)}%</p></div>`;
});
</script>
</body>
</html>
Run the Flask app locally with:
export DEEPFAKE_API_KEY="your-api-key"
python app.py
Then visit http://localhost:5000 in your browser to upload and analyze images.
Method 4: Real-Time Detection with a Webcam (OpenCV)
For applications that need to monitor video streams in real time, OpenCV combined with our API provides frame-by-frame analysis.
First, install OpenCV:
pip install opencv-python
Then use this script for real-time detection:
import cv2
import requests
import base64
import threading
import time
API_KEY = "your-api-key"
API_URL = "https://api.deepfakedetectionapi.ai/v1/detect"
class WebcamDetector:
def __init__(self, camera_id=0, check_interval=2):
self.camera = cv2.VideoCapture(camera_id)
self.check_interval = check_interval
self.last_check = 0
self.latest_result = None
self.analyzing = False
def analyze_frame(self, frame):
"""Send frame to API for analysis (runs in background)."""
try:
# Encode frame as base64
_, buffer = cv2.imencode(".jpg", frame)
image_data = base64.b64encode(buffer).decode()
# Send to API
headers = {"Authorization": f"Bearer {API_KEY}"}
payload = {"image_base64": image_data}
response = requests.post(API_URL, json=payload, headers=headers, timeout=10)
if response.status_code == 200:
self.latest_result = response.json()
self.analyzing = False
except Exception as e:
print(f"Analysis error: {e}")
self.analyzing = False
def run(self):
"""Main loop for webcam capture and display."""
while True:
ret, frame = self.camera.read()
if not ret:
break
# Analyze frame at intervals
current_time = time.time()
if current_time - self.last_check > self.check_interval and not self.analyzing:
self.analyzing = True
self.last_check = current_time
thread = threading.Thread(target=self.analyze_frame, args=(frame,))
thread.daemon = True
thread.start()
# Display results on frame
if self.latest_result:
is_deepfake = self.latest_result["is_deepfake"]
confidence = self.latest_result["confidence"]
color = (0, 0, 255) if is_deepfake else (0, 255, 0)
status = "DEEPFAKE" if is_deepfake else "REAL"
cv2.putText(frame, f"{status} ({confidence:.1%})",
(10, 30), cv2.FONT_HERSHEY_SIMPLEX,
0.7, color, 2)
cv2.imshow("Deepfake Detector", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
self.camera.release()
cv2.destroyAllWindows()
# Run the detector
if __name__ == "__main__":
detector = WebcamDetector(check_interval=2)
detector.run()
This script captures frames from your webcam every 2 seconds, sends them to the API for analysis in the background, and displays the results overlaid on the video feed in real time. Press 'q' to exit.
Performance Tips
Resize Images Before Sending
Smaller images process faster and use less bandwidth. Deepfake detection works well with images downsampled to 512x512 pixels or smaller:
from PIL import Image
def resize_image(image_path, max_size=512):
"""Resize image for faster processing."""
img = Image.open(image_path)
img.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
return img
Choose the Right Encoding Method
For images under 5MB, base64 encoding is simple and works well. For larger datasets or hosted images, use URLs directly to avoid encoding overhead.
Implement Rate Limiting
The API has rate limits to prevent abuse. Implement exponential backoff for retries:
import time
def make_request_with_backoff(url, data, max_retries=5):
for attempt in range(max_retries):
try:
response = requests.post(url, json=data, timeout=30)
if response.status_code == 429:
wait_time = 2 ** attempt
print(f"Rate limited. Waiting {wait_time}s...")
time.sleep(wait_time)
continue
return response
except requests.exceptions.Timeout:
if attempt < max_retries - 1:
time.sleep(2 ** attempt)
continue
raise
Pro Tip: For production systems processing thousands of images, consider batching your requests and using our enterprise API plan with higher rate limits. See our pricing page for options.
Next Steps
You now have four production-ready methods for integrating deepfake detection into your applications. Here's what to explore next:
- Visit our API documentation to learn about additional endpoints and parameters
- Try our interactive playground to test detection on your own images
- Check our pricing page to see options for scaling to production
- Review our quickstart guide for language-specific examples in other languages
For questions or support, reach out to our team at support@deepfakedetectionapi.ai. We're here to help you build secure, reliable deepfake detection into your workflow.