Deepface-Antispoofing Documentation
Video Demonstration
Watch this demonstration to see the Deepface-Antispoofing package in action:
Deepface-Antispoofing package demonstration showing real-time analysis of facial images
Overview
The deepface-antispoofing package is a comprehensive Python library for advanced facial analysis. Version 1.1.3 introduces enhanced capabilities including emotion detection, face mask detection, and comprehensive multi-model analysis.
This powerful package uses deep learning models for age/gender prediction, anti-spoofing detection, emotion analysis, face mask detection, and presentation attack detection, combined with Haar Cascade for robust face detection.
Core Detection Capabilities
Version 1.1.3 provides comprehensive facial analysis with six key detection capabilities:
- Age Estimation - Predicts subject's age range
- Gender Classification - Identifies apparent gender
- Authenticity Verification - Detects AI-generated deepfakes
- Presentation Attack Detection - Identifies printed photos and digital screens
- Emotion Recognition - Detects seven emotional states
- Face Mask Detection - Identifies mask usage
Age & Gender Detection
Accurately predicts age range and classifies gender with deep learning models.
- Age range prediction
- Gender classification
- Confidence scoring
Deepfake Detection
Flags faces generated or altered by AI models (GANs, diffusion models, etc.).
- Identifies GAN artifacts
- Detects unnatural facial symmetry
- Analyzes pixel-level inconsistencies
Presentation Attack Detection
Identify printed photos or digital screens used to spoof facial recognition.
- Screen reflection analysis
- Print texture detection
- Moire pattern recognition
Emotion Recognition
Detects seven emotional states: angry, disgust, fear, happy, neutral, sad, surprise.
- Real-time emotion tracking
- Multi-emotion probability
- Confidence scoring per emotion
Face Mask Detection
Identifies whether the person in the image is wearing a face mask or not.
- Mask presence detection
- Proper mask fit analysis
- Confidence probability scoring
Comprehensive Analysis
Complete facial analysis combining all models for holistic assessment.
- Combined model processing
- Unified response format
- Optimized performance
Input Methods
Image Upload
Analyze single images for replay/printed attacks with detailed forensic analysis
Webcam Stream
Real-time liveness verification with continuous authentication monitoring
Installation
To install the deepface-antispoofing package, use pip:
pip install deepface-antispoofing
Important Version Requirements:
- Python Version: Requires Python 3.11.2 or higher for optimal performance
- Package Version: Always use the latest version (v1.1.3) to avoid compatibility issues
- Dependencies: All dependencies are automatically installed with the latest compatible versions
The package automatically installs the following dependencies:
tensorflowopencv-pythonnumpyrequestsflask(for web interface)flask-cors
First-Time Setup
When you run the package for the first time, it automatically downloads the following files if they are not present in the current working directory:
- Age/Gender Model (
age_gender_model.h5): Downloaded to./models/age_gender_model.h5Used for predicting age and gender. - Anti-Spoofing Model (
anti_spoofing_model.h5): Downloaded to./models/anti_spoofing_model.h5Used for detecting real vs. fake faces. - Emotion Model (
emotion_model.h5): Downloaded to./models/emotion_model.h5Used for emotion recognition. - Face Mask Model (
face_mask_model.keras): Downloaded to./models/face_mask_model.kerasUsed for mask detection. - Printed Detection Model (
printed_detection_model_1.keras): Downloaded to./models/printed_detection_model_1.kerasUsed for presentation attack detection. - Haar Cascade File (
haarcascade_frontalface_default.xml): Downloaded to./data/haarcascade_frontalface_default.xmlUsed for face detection.
These files are stored in the models and data directories created in the current working directory. An internet connection is required for the initial download.
Project Structure
After the first run, the data and models directory structure is automatically created in the current working directory:
./
├── data/
│ └── haarcascade_frontalface_default.xml
├── models/
│ ├── age_gender_model.h5
│ ├── anti_spoofing_model.h5
│ ├── emotion_model.h5
│ ├── face_mask_model.keras
│ └── printed_detection_model_1.keras
├── templates/
│ ├── deepface.html
├── static/
│ ├── style.css
├── app.py
data/: Contains the Haar Cascade XML file for face detection.models/: Contains all deep learning models for comprehensive facial analysis.
Available Functions
analyze_image
Analyzes image for age, gender, and deepfake detection (AI-generated vs real faces).
analyze_deepface
Detects presentation attacks - identifies if face is live real or from printed media.
analyze_emotion
Detects seven emotional states: angry, disgust, fear, happy, neutral, sad, surprise.
analyze_face_mask
Detects whether the person in the image is wearing a face mask or not.
analyze_comprehensive
Comprehensive analysis combining all models - provides complete facial analysis in single call.
Code Examples
Example 1: Face Analysis with Age, Gender, and Deepfake Detection
The analyze_image method predicts age, gender, and whether the image contains a real or AI-generated face.
from deepface_antispoofing import DeepFaceAntiSpoofing
# Initialize the analyzer
deepface = DeepFaceAntiSpoofing()
# Analyze an image
result = deepface.analyze_image("path_to_image.jpg")
print(result)
Sample Response:
{
"age": 25,
"gender": {
"Male": 5.152494122739881e-05,
"Female": 0.9999485015869141
},
"dominant_gender": "Female",
"spoof": {
"Fake": 7.748603820800781e-07,
"Real": 0.9999992251396179
},
"dominant_spoof": "Real",
"timestamp": "2025-11-05 23:22:38"
}
Example 2: Anti-Spoofing Detection for Printed, Replay, or Presentation Attacks
The analyze_deepface method determines whether the face is real or part of a spoofing attack, such as a printed photo, replay attack, or presentation attack.
from deepface_antispoofing import DeepFaceAntiSpoofing
# Initialize the analyzer
deepface = DeepFaceAntiSpoofing()
# Analyze an image
result = deepface.analyze_deepface("path_to_image.jpg")
print(result)
Sample Response:
{
"printed_analysis": {
"Printed": 0.10731140524148941,
"Real": 0.8926885947585106
},
"dominant_printed": "Real",
"confidence": 0.8926885947585106,
"timestamp": "2025-11-05 23:23:34"
}
Example 3: Emotion Recognition Analysis
The analyze_emotion method detects seven different emotional states from facial expressions.
from deepface_antispoofing import DeepFaceAntiSpoofing
# Initialize the analyzer
deepface = DeepFaceAntiSpoofing()
# Analyze an image
result = deepface.analyze_emotion("path_to_image.jpg")
print(result)
Sample Response:
{
"emotions": {
"angry": 2.2382489987649024e-05,
"disgust": 6.113571515697913e-08,
"fear": 4.268830161890946e-05,
"happy": 0.9963662624359131,
"neutral": 0.0030167356599122286,
"sad": 3.199426646460779e-05,
"surprise": 0.0005198476719669998
},
"dominant_emotion": "happy",
"confidence": 0.9963662624359131,
"predicted_label": 3,
"timestamp": "2025-11-05 23:24:02"
}
Example 4: Face Mask Detection
The analyze_face_mask method detects whether the person in the image is wearing a face mask.
from deepface_antispoofing import DeepFaceAntiSpoofing
# Initialize the analyzer
deepface = DeepFaceAntiSpoofing()
# Analyze an image
result = deepface.analyze_face_mask("path_to_image.jpg")
print(result)
Sample Response:
{
"has_mask": false,
"with_mask_prob": 0.34883034229278564,
"without_mask_prob": 0.6511696577072144,
"confidence": 0.6511696577072144,
"mask_status": "Without Mask",
"timestamp": "2025-11-05 23:24:52"
}
Example 5: Comprehensive Facial Analysis
The analyze_comprehensive method provides complete facial analysis by combining all models in a single call.
from deepface_antispoofing import DeepFaceAntiSpoofing
# Initialize the analyzer
deepface = DeepFaceAntiSpoofing()
# Analyze an image
result = deepface.analyze_comprehensive("path_to_image.jpg")
print(result)
Sample Response:
{
"age_gender": {
"age": 25,
"gender": {
"Male": 5.152494122739881e-05,
"Female": 0.9999485015869141
},
"dominant_gender": "Female",
"spoof": {
"Fake": 7.748603820800781e-07,
"Real": 0.9999992251396179
},
"dominant_spoof": "Real",
"timestamp": "2025-11-05 23:25:17"
},
"printed_detection": {
"printed_analysis": {
"Printed": 0.10731140524148941,
"Real": 0.8926885947585106
},
"dominant_printed": "Real",
"confidence": 0.8926885947585106,
"timestamp": "2025-11-05 23:25:18"
},
"emotion": {
"emotions": {
"angry": 2.2382489987649024e-05,
"disgust": 6.113571515697913e-08,
"fear": 4.268830161890946e-05,
"happy": 0.9963662624359131,
"neutral": 0.0030167356599122286,
"sad": 3.199426646460779e-05,
"surprise": 0.0005198476719669998
},
"dominant_emotion": "happy",
"confidence": 0.9963662624359131,
"predicted_label": 3,
"timestamp": "2025-11-05 23:25:19"
},
"face_mask": {
"has_mask": false,
"with_mask_prob": 0.34883034229278564,
"without_mask_prob": 0.6511696577072144,
"confidence": 0.6511696577072144,
"mask_status": "Without Mask",
"timestamp": "2025-11-05 23:25:20"
},
"timestamp": "2025-11-05 23:25:20"
}
Demo
Try the package by uploading an image below. This demo uses a Flask app to process the image with the DeepFaceAntiSpoofing class. Below the demo, you'll find the source code for the HTML, CSS, and JavaScript used, which you can copy and modify for your own projects.
Demo Source Code
The demo uses a simple Flask app and a web interface. Below is the code for the Flask app (app.py) and the web interface (deepface.html), split into HTML, CSS, and JavaScript tabs. You can copy this code to create your own application.
Flask App (app.py)
import os
import cv2
from flask import Flask, render_template, request, jsonify, Response
from flask_cors import CORS
from deepface_antispoofing import DeepFaceAntiSpoofing
import datetime
app = Flask(__name__)
CORS(app) # Enable CORS for all routes
# Config for anti-spoofing
UPLOAD_FOLDER = "static/uploads"
TEMP_FOLDER = "static/temp"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(TEMP_FOLDER, exist_ok=True)
camera = cv2.VideoCapture(0)
# Initialize DeepFaceAntiSpoofing for deepfake analysis
try:
deepface_analyzer = DeepFaceAntiSpoofing()
except Exception as e:
print(f"Failed to initialize DeepFaceAntiSpoofing: {str(e)}")
deepface_analyzer = None
def generate_frames():
while True:
success, frame = camera.read()
if not success:
break
ret, buffer = cv2.imencode(".jpg", frame)
frame = buffer.tobytes()
yield (b"--frame\r\n"
b"Content-Type: image/jpeg\r\n\r\n" + frame + b"\r\n")
@app.route("/")
def index():
return render_template("deepface.html")
@app.route("/video_feed")
def video_feed():
return Response(generate_frames(), mimetype="multipart/x-mixed-replace; boundary=frame")
@app.route("/analyze_frame", methods=["POST"])
def analyze_frame():
"""Capture current webcam frame and analyze using DeepFaceAntiSpoofing."""
if deepface_analyzer is None:
return jsonify({"success": False, "error": "DeepFaceAntiSpoofing not initialized"})
success, frame = camera.read()
if not success:
return jsonify({"success": False, "error": "Failed to capture frame"})
temp_path = os.path.join(TEMP_FOLDER, "capture.jpg")
cv2.imwrite(temp_path, frame)
result = deepface_analyzer.analyze_deepface(temp_path)
return jsonify(result)
@app.route("/upload_anti", methods=["POST"])
def upload_anti_file():
if deepface_analyzer is None:
return jsonify({"success": False, "error": "DeepFaceAntiSpoofing not initialized"})
if "file" not in request.files:
return jsonify({"success": False, "error": "No file uploaded"})
file = request.files["file"]
if file.filename == "":
return jsonify({"success": False, "error": "Empty filename"})
path = os.path.join(UPLOAD_FOLDER, file.filename)
file.save(path)
result = deepface_analyzer.analyze_deepface(path)
print(result)
return jsonify(result)
@app.route("/upload_deep", methods=["POST"])
def upload_deep_image():
if deepface_analyzer is None:
return jsonify({"error": "DeepFaceAntiSpoofing not initialized", "success": False}), 500
if 'image' not in request.files:
return jsonify({"error": "No image uploaded", "success": False}), 400
file = request.files['image']
if file.filename == '':
return jsonify({"error": "No image selected", "success": False}), 400
image_path = os.path.join(UPLOAD_FOLDER, file.filename)
file.save(image_path)
try:
result = deepface_analyzer.analyze_image(image_path)
return jsonify(result)
except Exception as e:
return jsonify({"error": f"Analysis failed: {str(e)}", "success": False}), 500
@app.route("/analyze_face_mask", methods=["POST"])
def analyze_face_mask():
"""Analyze image for face mask detection."""
if deepface_analyzer is None:
return jsonify({"error": "DeepFaceAntiSpoofing not initialized"})
success, frame = camera.read()
if not success:
return jsonify({"error": "Failed to capture frame"})
try:
# Enhance the captured frame
frame = cv2.convertScaleAbs(frame, alpha=1.3, beta=15)
# Save the enhanced frame
temp_path = os.path.join(TEMP_FOLDER, "mask_capture.jpg")
cv2.imwrite(temp_path, frame, [cv2.IMWRITE_JPEG_QUALITY, 95])
# CORRECTED: Use analyze_face_mask method instead of analyze_image
result = deepface_analyzer.analyze_face_mask(temp_path)
return jsonify(result)
except Exception as e:
return jsonify({"error": f"Face mask analysis failed: {str(e)}"})
@app.route("/upload_face_mask", methods=["POST"])
def upload_face_mask_file():
if deepface_analyzer is None:
return jsonify({"error": "DeepFaceAntiSpoofing not initialized"})
if "file" not in request.files:
return jsonify({"error": "No file uploaded"})
file = request.files["file"]
if file.filename == "":
return jsonify({"error": "Empty filename"})
path = os.path.join(UPLOAD_FOLDER, file.filename)
file.save(path)
# CORRECTED: Use analyze_face_mask method
result = deepface_analyzer.analyze_face_mask(path)
print(result)
return jsonify(result)
# Emotion Analysis Endpoints
@app.route("/analyze_emotion", methods=["POST"])
def analyze_emotion():
"""Analyze webcam frame for emotion detection."""
if deepface_analyzer is None:
return jsonify({"error": "DeepFaceAntiSpoofing not initialized"})
success, frame = camera.read()
if not success:
return jsonify({"error": "Failed to capture frame"})
try:
temp_path = os.path.join(TEMP_FOLDER, "emotion_capture.jpg")
cv2.imwrite(temp_path, frame)
# CORRECTED: Use analyze_emotion method instead of analyze_image
result = deepface_analyzer.analyze_emotion(temp_path)
return jsonify(result)
except Exception as e:
return jsonify({"error": f"Emotion analysis failed: {str(e)}"})
@app.route("/upload_emotion", methods=["POST"])
def upload_emotion_file():
if deepface_analyzer is None:
return jsonify({"error": "DeepFaceAntiSpoofing not initialized"})
if "file" not in request.files:
return jsonify({"error": "No file uploaded"})
file = request.files["file"]
if file.filename == "":
return jsonify({"error": "Empty filename"})
path = os.path.join(UPLOAD_FOLDER, file.filename)
file.save(path)
try:
# CORRECTED: Use analyze_emotion method
result = deepface_analyzer.analyze_emotion(path)
return jsonify(result)
except Exception as e:
return jsonify({"error": f"Emotion analysis failed: {str(e)}"})
# Comprehensive Analysis Endpoints
@app.route("/comprehensive_analysis_capture", methods=["POST"])
def comprehensive_analysis_capture():
"""Comprehensive analysis from webcam."""
if deepface_analyzer is None:
return jsonify({"error": "DeepFaceAntiSpoofing not initialized"})
success, frame = camera.read()
if not success:
return jsonify({"error": "Failed to capture frame"})
try:
temp_path = os.path.join(TEMP_FOLDER, "comprehensive_capture.jpg")
cv2.imwrite(temp_path, frame)
# CORRECTED: Use analyze_comprehensive method
result = deepface_analyzer.analyze_comprehensive(temp_path)
return jsonify(result)
except Exception as e:
return jsonify({"error": f"Comprehensive analysis failed: {str(e)}"})
@app.route("/comprehensive_analysis", methods=["POST"])
def comprehensive_analysis():
"""Comprehensive analysis from uploaded file."""
if deepface_analyzer is None:
return jsonify({"error": "DeepFaceAntiSpoofing not initialized"})
if "file" not in request.files:
return jsonify({"error": "No file uploaded"})
file = request.files["file"]
if file.filename == "":
return jsonify({"error": "Empty filename"})
path = os.path.join(UPLOAD_FOLDER, file.filename)
file.save(path)
try:
# CORRECTED: Use analyze_comprehensive method
result = deepface_analyzer.analyze_comprehensive(path)
return jsonify(result)
except Exception as e:
return jsonify({"error": f"Comprehensive analysis failed: {str(e)}"})
if __name__ == "__main__":
try:
app.run(debug=True)
except Exception as e:
print(f"Failed to start main Flask app: {str(e)}")
raise
Web Interface (deepface.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Face Analysis System</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
/* CSS content is displayed in the CSS tab */
</style>
</head>
<body>
<div class="app-container">
<header>
<div class="header-content">
<div class="logo">
<i class="fas fa-shield-alt logo-icon"></i>
<h1 class="logo-text">Advanced Face Analysis System</h1>
</div>
</div>
</header>
<div class="tabs-container">
<div class="tabs">
<button class="tab-btn active" data-tab="deep">
<i class="fas fa-robot"></i> Deepfake Analysis
</button>
<button class="tab-btn" data-tab="anti">
<i class="fas fa-print"></i> Anti-Spoofing
</button>
<button class="tab-btn" data-tab="emotion">
<i class="fas fa-smile"></i> Emotion Analysis
</button>
<button class="tab-btn" data-tab="mask">
<i class="fas fa-head-side-mask"></i> Face Mask Detection
</button>
<button class="tab-btn" data-tab="comprehensive">
<i class="fas fa-brain"></i> Comprehensive Analysis
</button>
</div>
</div>
<main>
<!-- Deepfake Tab -->
<div id="deep-tab" class="tab-content active">
<div class="dashboard-deep">
<!-- Upload Area -->
<div class="card">
<div class="card-header">
<h2 class="card-title">
<i class="fas fa-cloud-upload-alt card-icon"></i>
Image Upload
</h2>
</div>
<div class="card-body">
<div class="upload-area" id="uploadAreaDeep">
<i class="fas fa-cloud-upload-alt upload-icon"></i>
<p class="upload-text">Drag & Drop your image here or click to browse</p>
<input type="file" id="imageInputDeep" accept="image/*" class="file-input">
</div>
<img id="uploadedImageDeep" class="image-preview" alt="Uploaded Image Preview">
<div class="action-buttons">
<button id="analyzeBtnDeep" class="btn btn-primary" disabled>
<i class="fas fa-search"></i> Analyze Image
</button>
<button id="resetBtnDeep" class="btn btn-outline">
<i class="fas fa-redo"></i> Reset
</button>
</div>
<div class="error-message" id="errorMessageDeep"></div>
<!-- REMOVED: <div class="result" id="resultDeep"></div> FROM HERE -->
</div>
</div>
<!-- Result Area -->
<div class="card">
<div class="card-header">
<h2 class="card-title">
<i class="fas fa-chart-bar card-icon"></i>
Analysis Results
</h2>
</div>
<div class="card-body">
<div id="initialMessageDeep">
<p>Upload an image to analyze for deepfake detection, age, gender, and other facial attributes.</p>
</div>
<div class="loading" id="loadingResultsDeep" style="display: none;">
<div class="spinner"></div>
<p class="loading-text">Analyzing...</p>
</div>
<div class="error-message" id="errorMessageResultsDeep" style="display: none;"></div>
<div class="result" id="resultDeep"></div> <!-- MOVED RESULTS HERE -->
</div>
</div>
</div>
</div>
<!-- Anti-Spoofing Tab -->
<div id="anti-tab" class="tab-content">
<div class="dashboard">
<!-- Webcam Card -->
<div class="card">
<div class="card-header">
<h2 class="card-title">
<i class="fas fa-video card-icon"></i>
Live Printed Detection
</h2>
<div class="status-indicator">
<i class="fas fa-circle" style="color: var(--success);"></i>
<span>Camera Active</span>
</div>
</div>
<div class="card-body">
<div class="webcam-container">
<img id="videoFeed" src="/video_feed" alt="Webcam Feed" style="transform: scaleX(-1); width: 100%; height: 100%;">
</div>
<div class="webcam-button-container">
<button id="captureBtn" class="btn btn-primary btn-lg">
<i class="fas fa-camera"></i>
Capture & Analyze
</button>
</div>
<div class="loading" id="loadingCam">
<div class="spinner"></div>
<p class="loading-text">Analyzing for printed images...</p>
</div>
<div class="result" id="camResult"></div>
</div>
</div>
<!-- Upload Card for Anti-Spoofing -->
<div class="card">
<div class="card-header">
<h2 class="card-title">
<i class="fas fa-cloud-upload-alt card-icon"></i>
Image Analysis
</h2>
</div>
<div class="card-body">
<div class="upload-area" id="uploadAreaAnti">
<i class="fas fa-file-upload upload-icon"></i>
<p class="upload-text">Drag & drop an image or click to browse</p>
<input type="file" id="fileInputAnti" accept="image/*" class="file-input">
</div>
<img id="uploadedImageAnti" class="image-preview" alt="Uploaded Image Preview">
<div class="action-buttons">
<button id="analyzeBtnAnti" class="btn btn-primary" disabled>
<i class="fas fa-search"></i> Analyze Image
</button>
<button id="resetBtnAnti" class="btn btn-outline">
<i class="fas fa-redo"></i> Reset
</button>
</div>
<div class="loading" id="loadingUploadAnti">
<div class="spinner"></div>
<p class="loading-text">Processing uploaded image...</p>
</div>
<div class="result" id="uploadResultAnti"></div>
</div>
</div>
</div>
</div>
<!-- Emotion Analysis Tab -->
<div id="emotion-tab" class="tab-content">
<div class="dashboard">
<!-- Webcam Card for Emotion -->
<div class="card">
<div class="card-header">
<h2 class="card-title">
<i class="fas fa-smile card-icon"></i>
Live Emotion Detection
</h2>
<div class="status-indicator">
<i class="fas fa-circle" style="color: var(--success);"></i>
<span>Camera Active</span>
</div>
</div>
<div class="card-body">
<div class="webcam-container">
<img id="videoFeedEmotion" src="/video_feed" alt="Webcam Feed" style="transform: scaleX(-1); width: 100%; height: 100%;">
</div>
<div class="webcam-button-container">
<button id="captureBtnEmotion" class="btn btn-primary btn-lg">
<i class="fas fa-camera"></i>
Capture & Analyze Emotions
</button>
</div>
<div class="loading" id="loadingCamEmotion">
<div class="spinner"></div>
<p class="loading-text">Analyzing facial emotions...</p>
</div>
<div class="result" id="camResultEmotion"></div>
</div>
</div>
<!-- Upload Card for Emotion -->
<div class="card">
<div class="card-header">
<h2 class="card-title">
<i class="fas fa-cloud-upload-alt card-icon"></i>
Image Emotion Analysis
</h2>
</div>
<div class="card-body">
<div class="upload-area" id="uploadAreaEmotion">
<i class="fas fa-file-upload upload-icon"></i>
<p class="upload-text">Drag & drop an image or click to browse</p>
<input type="file" id="fileInputEmotion" accept="image/*" class="file-input">
</div>
<img id="uploadedImageEmotion" class="image-preview" alt="Uploaded Image Preview">
<div class="action-buttons">
<button id="analyzeBtnEmotion" class="btn btn-primary" disabled>
<i class="fas fa-search"></i> Analyze Emotions
</button>
<button id="resetBtnEmotion" class="btn btn-outline">
<i class="fas fa-redo"></i> Reset
</button>
</div>
<div class="loading" id="loadingUploadEmotion">
<div class="spinner"></div>
<p class="loading-text">Processing emotions...</p>
</div>
<div class="result" id="uploadResultEmotion"></div>
</div>
</div>
</div>
</div>
<!-- Face Mask Detection Tab -->
<div id="mask-tab" class="tab-content">
<div class="dashboard">
<!-- Webcam Card for Mask -->
<div class="card">
<div class="card-header">
<h2 class="card-title">
<i class="fas fa-head-side-mask card-icon"></i>
Live Mask Detection
</h2>
<div class="status-indicator">
<i class="fas fa-circle" style="color: var(--success);"></i>
<span>Camera Active</span>
</div>
</div>
<div class="card-body">
<div class="webcam-container">
<img id="videoFeedMask" src="/video_feed" alt="Webcam Feed" style="transform: scaleX(-1); width: 100%; height: 100%;">
</div>
<div class="webcam-button-container">
<button id="captureBtnMask" class="btn btn-primary btn-lg">
<i class="fas fa-camera"></i>
Capture & Analyze Mask
</button>
</div>
<div class="loading" id="loadingCamMask">
<div class="spinner"></div>
<p class="loading-text">Analyzing for face mask...</p>
</div>
<div class="result" id="camResultMask"></div>
</div>
</div>
<!-- Upload Card for Mask -->
<div class="card">
<div class="card-header">
<h2 class="card-title">
<i class="fas fa-cloud-upload-alt card-icon"></i>
Image Mask Detection
</h2>
</div>
<div class="card-body">
<div class="upload-area" id="uploadAreaMask">
<i class="fas fa-file-upload upload-icon"></i>
<p class="upload-text">Drag & drop an image or click to browse</p>
<input type="file" id="fileInputMask" accept="image/*" class="file-input">
</div>
<img id="uploadedImageMask" class="image-preview" alt="Uploaded Image Preview">
<div class="action-buttons">
<button id="analyzeBtnMask" class="btn btn-primary" disabled>
<i class="fas fa-search"></i> Analyze Mask
</button>
<button id="resetBtnMask" class="btn btn-outline">
<i class="fas fa-redo"></i> Reset
</button>
</div>
<div class="loading" id="loadingUploadMask">
<div class="spinner"></div>
<p class="loading-text">Processing mask detection...</p>
</div>
<div class="result" id="uploadResultMask"></div>
</div>
</div>
</div>
</div>
<!-- Comprehensive Analysis Tab -->
<div id="comprehensive-tab" class="tab-content">
<div class="dashboard">
<!-- Webcam Card for Comprehensive -->
<div class="card">
<div class="card-header">
<h2 class="card-title">
<i class="fas fa-brain card-icon"></i>
Live Comprehensive Analysis
</h2>
<div class="status-indicator">
<i class="fas fa-circle" style="color: var(--success);"></i>
<span>Camera Active</span>
</div>
</div>
<div class="card-body">
<div class="webcam-container">
<img id="videoFeedComprehensive" src="/video_feed" alt="Webcam Feed" style="transform: scaleX(-1); width: 100%; height: 100%;">
</div>
<div class="webcam-button-container">
<button id="captureBtnComprehensive" class="btn btn-primary btn-lg">
<i class="fas fa-camera"></i>
Complete Analysis
</button>
</div>
<div class="loading" id="loadingCamComprehensive">
<div class="spinner"></div>
<p class="loading-text">Running comprehensive analysis...</p>
</div>
<div class="result" id="camResultComprehensive"></div>
</div>
</div>
<!-- Upload Card for Comprehensive -->
<div class="card">
<div class="card-header">
<h2 class="card-title">
<i class="fas fa-cloud-upload-alt card-icon"></i>
Comprehensive Image Analysis
</h2>
</div>
<div class="card-body">
<div class="upload-area" id="uploadAreaComprehensive">
<i class="fas fa-file-upload upload-icon"></i>
<p class="upload-text">Drag & drop an image or click to browse</p>
<input type="file" id="fileInputComprehensive" accept="image/*" class="file-input">
</div>
<img id="uploadedImageComprehensive" class="image-preview" alt="Uploaded Image Preview">
<div class="action-buttons">
<button id="analyzeBtnComprehensive" class="btn btn-primary" disabled>
<i class="fas fa-search"></i> Complete Analysis
</button>
<button id="resetBtnComprehensive" class="btn btn-outline">
<i class="fas fa-redo"></i> Reset
</button>
</div>
<div class="loading" id="loadingUploadComprehensive">
<div class="spinner"></div>
<p class="loading-text">Running all analyses...</p>
</div>
<div class="result" id="uploadResultComprehensive"></div>
</div>
</div>
</div>
</div>
</main>
</div>
<script>
/* JavaScript content is displayed in the JavaScript tab */
</script>
</body>
</html>
To use this demo code:
- Save the Flask app code as
app.pyin your project directory. - Create a
templatesfolder and save the web interface code asdeepface.html. - Create a
staticfolder for storing uploaded images (e.g.,static/uploaded_image.jpg). - Install required packages:
pip install flask flask-cors deepface-antispoofing tf-keras. - Run the Flask app:
python app.py. - Open
http://localhost:5000in a browser to use the demo.
Dependencies
The package requires the following Python libraries, which are automatically installed via pip:
tensorflow: For deep learning model execution.opencv-python: For image processing and face detection.numpy: For numerical computations.requests: For downloading models and Haar Cascade files.flask: For web interface functionality.pillow: For image processing utilities.tf-keras: For Keras model compatibility.
Troubleshooting
Below are common issues and their solutions:
-
Issue: Installation fails with Python version errors.
- Solution: Ensure you're using Python 3.11.2 or higher. Check your version with
python --versionand upgrade if necessary.
- Solution: Ensure you're using Python 3.11.2 or higher. Check your version with
-
Issue: "Failed to download" errors during first-time setup.
- Solution: Ensure you have an active internet connection. Check the URLs in the package code for accessibility.
-
Issue: "ModuleNotFoundError: No module named 'tf_keras'" error.
- Solution: Install the required dependency with
pip install tf-keras
- Solution: Install the required dependency with
-
Issue: "No face detected" or "Multiple faces detected" errors.
- Solution: Ensure the image contains exactly one clear, front-facing face. Use high-resolution images with good lighting.
-
Issue: Webcam not working.
- Solution: Check camera permissions and ensure no other application is using the camera.
-
Issue: Real images classified as fake by the anti-spoofing model.
- Solution: Check the spoof probability in the output (e.g.,
result['spoof']['Real']). If it's close to 0.5, adjust the threshold in the package code (e.g., changeis_real = spoof_prob > 0.5to0.3). If the issue persists, the model may need retraining with a diverse dataset.
- Solution: Check the spoof probability in the output (e.g.,
-
Issue: Version compatibility problems.
- Solution: Always use the latest version of deepface-antispoofing (v1.1.3) and ensure Python version is 3.11.2 or higher. Avoid mixing with older versions.
Support
For issues, feature requests, or contributions, visit the IP Softech or contact the author at ipsoftechsolutions@gmail.com.