Views
No views yet
| Metric | Training Set | Validation Set |
|---|---|---|
| Accuracy | 80.69% | 99.75% |
| EER (Equal Error Rate) | 20.83% | 1% |
| AUC-ROC | TBD | TBD |
1# Core dependencies
2pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
3pip install scikit-learn pillow tqdm numpy opencv-python
4
5# For inference (YOLO face detection)
6pip install onnxruntime-gpu huggingface_hubdataset_antispoofing_cropped/
├── real_frame_cropped/ # Genuine face videos
│ ├── video_001/
│ │ ├── frame_0001.jpg
│ │ ├── frame_0002.jpg
│ │ └── ...
│ └── video_002/
│ └── ...
└── attack_frame_cropped2/ # Spoofing attack videos
├── video_001/
│ ├── frame_0001.jpg
│ └── ...
└── video_002/
└── ...1# Download inference script
2wget https://huggingface.co/YOUR_USERNAME/Face_AntiSpoofing/resolve/main/inference.py
3
4# Download FULL trained model (includes backbone + temporal + classifier)
5wget https://huggingface.co/YOUR_USERNAME/Face_AntiSpoofing/resolve/main/antispoofing_full.pth
6
7# Download YOLO face detector (or auto-download on first run)
8wget https://huggingface.co/arnabdhar/YOLOv8-Face-Detection/resolve/main/model.onnx -O yolov8s-face-lindevs.onnx1from inference import AntiSpoofingDetector
2
3# Initialize detector (NEW: single file!)
4detector = AntiSpoofingDetector(
5 model_path="antispoofing_full.pth", # ← Full checkpoint
6 yolo_model_path="yolov8s-face-lindevs.onnx",
7 device="cuda",
8 threshold=0.5
9)
10
11# Test single image
12result = detector.predict_image("test.jpg")
13print(result)
14# Output: {'prediction': 'GENUINE', 'confidence': 0.32, 'is_attack': False}1# Test video file
2result = detector.predict_video("test_video.mp4", sample_frames=30)
3print(f"Prediction: {result['prediction']}")
4print(f"Confidence: {result['confidence']:.4f}")
5print(f"Frame scores: {result['frame_scores']}")1# Run webcam detection
2detector.run_webcam(camera_id=0, frame_skip=2)
3# Press 'q' to quit, 's' to show statisticsreal_frame_cropped and attack_frame_cropped2 folders.1# Download training script
2wget https://huggingface.co/YOUR_USERNAME/Face_AntiSpoofing/resolve/main/train_antispoofing.py
3
4# Download face recognition backbone (ONLY needed for first training)
5wget https://huggingface.co/biometric-ai-lab/Face_Recognition/resolve/main/faceRecognition_arcface_ckpt.pth1# First time training (will load backbone from faceRecognition_arcface_ckpt.pth)
2python train_antispoofing.pyantispoofing_full.pth existsfaceRecognition_arcface_ckpt.pthantispoofing_full.pth (includes backbone + temporal + classifier)1# Next time (will load full model from antispoofing_full.pth)
2python train_antispoofing.pyantispoofing_full.pth exists1import torch
2from train_antispoofing import (
3 DeepFakeModel, FaceVideoDataset, train_model,
4 transforms, DataLoader, ConcatDataset
5)
6
7# Define augmentation
8transform_train = transforms.Compose([
9 transforms.Resize((256, 256)),
10 transforms.RandomRotation(45),
11 transforms.RandomAffine(0, translate=(0.1, 0.1), scale=(0.9, 1.1), shear=10),
12 transforms.RandomPerspective(0.2, p=0.3),
13 transforms.RandomCrop((224, 224)),
14 transforms.RandomHorizontalFlip(p=0.5),
15 transforms.ColorJitter(0.3, 0.3, 0.3, 0.15),
16 transforms.ToTensor(),
17 transforms.RandomErasing(p=0.3),
18 transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
19])
20
21# Load datasets
22real_train = FaceVideoDataset(
23 root_dir="path/to/real_frame_cropped",
24 label=0, num_frames=10, clips_per_video=70,
25 transform=transform_train
26)
27
28fake_train = FaceVideoDataset(
29 root_dir="path/to/attack_frame_cropped2",
30 label=1, num_frames=10, clips_per_video=70,
31 transform=transform_train
32)
33
34train_dataset = ConcatDataset([real_train, fake_train])
35train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
36
37# ============================================================
38# SMART MODEL CREATION
39# ============================================================
40resume_checkpoint = "antispoofing_full.pth"
41backbone_file = "faceRecognition_arcface_ckpt.pth"
42
43# Check if full checkpoint exists
44if os.path.exists(resume_checkpoint):
45 print("✓ Found checkpoint, loading full model...")
46 model = DeepFakeModel(
47 backbone_ckpt=None, # Don't load backbone separately
48 freeze_backbone=True
49 )
50else:
51 print("✓ No checkpoint, loading backbone separately...")
52 model = DeepFakeModel(
53 backbone_ckpt=backbone_file, # Load backbone for first training
54 freeze_backbone=True
55 )
56
57# Train (will auto-resume if checkpoint exists)
58train_model(
59 model=model,
60 train_loader=train_loader,
61 val_loader=val_loader,
62 epochs=15,
63 lr_temporal=1e-4,
64 lr_head=3e-4,
65 device="cuda",
66 save_path="antispoofing_full.pth",
67 resume_from=resume_checkpoint # Auto-load if exists
68)test_image.py:1from inference import AntiSpoofingDetector
2
3detector = AntiSpoofingDetector(
4 model_path="antispoofing_full.pth", # ← Single file!
5 yolo_model_path="yolov8s-face-lindevs.onnx",
6 threshold=0.5
7)
8
9result = detector.predict_image("test_photo.jpg")
10
11print(f"\n{'='*50}")
12print(f"Prediction: {result['prediction']}")
13print(f"Confidence: {result['confidence']:.4f}")
14print(f"Is Attack: {result['is_attack']}")
15if result['bbox']:
16 x1, y1, x2, y2, conf = result['bbox']
17 print(f"Face Location: ({x1}, {y1}) to ({x2}, {y2})")
18print(f"{'='*50}")test_videos.py:1from inference import AntiSpoofingDetector
2import glob
3
4detector = AntiSpoofingDetector(
5 model_path="antispoofing_full.pth",
6 yolo_model_path="yolov8s-face-lindevs.onnx",
7 threshold=0.5
8)
9
10video_files = glob.glob("test_videos/*.mp4")
11
12results = []
13for video_path in video_files:
14 result = detector.predict_video(video_path, sample_frames=30)
15 results.append({
16 'video': video_path,
17 'prediction': result['prediction'],
18 'confidence': result['confidence']
19 })
20
21# Print summary
22print("\n" + "="*60)
23print("BATCH TEST RESULTS")
24print("="*60)
25for r in results:
26 status = "✓ REAL" if r['prediction'] == "GENUINE" else "✗ FAKE"
27 print(f"{status:10} | {r['confidence']:.4f} | {r['video']}")
28print("="*60)run_webcam.py:1from inference import AntiSpoofingDetector
2
3detector = AntiSpoofingDetector(
4 model_path="antispoofing_full.pth",
5 yolo_model_path="yolov8s-face-lindevs.onnx",
6 threshold=0.2, # Lower threshold for real-time (more sensitive)
7 num_frames=10
8)
9
10# Run webcam
11# Press 'q' to quit, 's' to show statistics
12detector.run_webcam(camera_id=0, frame_skip=2)python run_webcam.pyInput: (Batch, 10 frames, 3, 224, 224)
↓
Backbone: Wide ResNet-101-2 [Layer 1-2 only]
- Transfer learning from face recognition
- Output: (Batch, 10, 512, H, W)
↓
Temporal Encoder: Transformer (8 heads, 4 layers)
- Positional encoding for temporal order
- Output: (Batch, 512)
↓
Classifier: Linear(512→256→1)
- GELU activation + Dropout
- Output: (Batch, 1) logits → sigmoid → probability
↓
Decision: probability > threshold → FAKE, else REAL1{
2 'prediction': 'GENUINE' or 'SPOOFING_ATTACK',
3 'confidence': 0.0-1.0, # Probability of being ATTACK
4 'is_attack': True/False,
5 'bbox': (x1, y1, x2, y2, conf) or None
6}1# Strict mode (fewer false negatives, more false positives)
2detector = AntiSpoofingDetector(
3 model_path="antispoofing_full.pth",
4 threshold=0.2
5)
6
7# Balanced mode (default)
8detector = AntiSpoofingDetector(
9 model_path="antispoofing_full.pth",
10 threshold=0.5
11)
12
13# Permissive mode (fewer false positives, more false negatives)
14detector = AntiSpoofingDetector(
15 model_path="antispoofing_full.pth",
16 threshold=0.7
17)Load: faceRecognition_arcface_ckpt.pth (backbone only)
↓
Train: temporal encoder + classifier
↓
Save: antispoofing_full.pth (backbone + temporal + classifier)Load: antispoofing_full.pth (everything)
↓
Resume: from saved epoch
↓
Save: antispoofing_full.pth (updated)Face_AntiSpoofing/
├── train_antispoofing.py # Training script
├── inference.py # Inference API
├── README.md # This file
├── requirements.txt # Dependencies
├── models/
│ ├── antispoofing_full.pth # ← FULL checkpoint (all weights)
│ ├── faceRecognition_arcface_ckpt.pth # ← Backbone (only for first training)
│ └── yolov8s-face-lindevs.onnx # ← Face detector
├── examples/
│ ├── test_image.py
│ ├── test_videos.py
│ └── run_webcam.py
└── dataset_antispoofing_cropped/
├── real_frame_cropped/
└── attack_frame_cropped2/