Skip to main content

DeepClip

License Stars Release PyPI Python PyTorch Hugging Face Spaces

Region-Aware Face Forgery Artifact Description with Contrastive Language-Image Pre-training
4 face regions × 5 artifact types: not just whether a face is fake, but where and how.

DeepClip architecture

📌 Contents

💡 What DeepClip Predicts

DeepClip scores a face image against CLIP text captions. Besides the fake probability, it gives an artifact score for each pair of a face region and a forgery artifact type, so you can see where and what kind of forgery the model sees.

Values
Region face, eyes, nose, mouth
Artifact type blur, color, texture, structure, blend
  • Fake probability: 1 - p_real, where p_real is the score of the caption "a photo of a real face."
  • Artifact scores: 4 regions × 5 types = 20 captions such as "... blending artifacts on the mouth", each a probability in [0, 1].

DeepClip artifact map (region × type)

🏗️ Architecture

DeepClip combines the MS-Eff-GCViT image encoder of DeepGuard with the text encoder of CLIP.

  • (1) Training: every fake face gets a caption built from one (region, artifact type) pair sampled from its pair_label. The image encoder (trainable) is aligned with the frozen CLIP text embeddings with a multi-positive sigmoid loss (SigLIP). The 21 caption embeddings are computed once and kept in a table, so the text encoder is not run during training.
    • Text fine-tuning (*_v2): the CLIP text encoder is part of the model and is trained with LoRA (lora_r, lora_alpha, lora_drop) on the q, k, v and out projections of every text attention block, while the CLIP weights stay frozen. The 21 captions are embedded by the text encoder at every step, so the caption embeddings adapt together with the image encoder.
  • (2) Inference: the similarity to "a photo of a real face." gives the fake probability, and the similarity to the 20 region–artifact captions gives the artifact map.

🧬 Model Zoo

Model Resolution Image Encoder Text Encoder Params FLOPs Model Config
⚡ deepclip_b0 224 X 224 ms_eff_gcvit_b0 CLIP ViT-B/16 (frozen) 8.82M 0.83G spec
🔥 deepclip_b5 384 X 384 ms_eff_gcvit_b5 CLIP ViT-L/14 (frozen) 50.61M 13.26G spec
⚡ deepclip_b0_v2 224 X 224 ms_eff_gcvit_b0 CLIP ViT-B/16 (LoRA) 72.44M 15.18G spec
🔥 deepclip_b5_v2 384 X 384 ms_eff_gcvit_b5 CLIP ViT-L/14 (LoRA) 174.56M 45.49G spec

deepclip_b0 and deepclip_b5 don't keep the text encoder: the frozen CLIP text encoder embeds the 21 captions once and only the embeddings (text_table) are kept, so Params and FLOPs (multiply-accumulates, one image) are of the image encoder. *_v2 keep the whole text encoder with LoRA (r=4: 0.20M for ViT-B/16, 0.29M for ViT-L/14), so Params are image + text encoder and FLOPs are one image plus the 21 captions. At inference the caption embeddings are cached, so each further image costs only the image encoder (0.83G for b0, 13.26G for b5).

🤗 Try It Live: Hugging Face Spaces

Try DeepClip in the browser on Hugging Face Spaces, with no install needed.

📝
Face Forgery Artifact Description
Upload an image or video → fake probability + region × artifact captions in text

Open Face Forgery Artifact Description in Spaces

💛 Enjoying the demos? Please leave a ❤️ like on the Space — it means a lot to us!

🔮 Predict Image & Video

Both options detect the largest face with YOLO (yolov8n-face, downloaded to ~/.cache/deepclip on the first run), crop it with a margin and run DeepClip on the crop.

Option A: HuggingFace

The pretrained models are on the Hugging Face Hub as KoreaPeter/deepclip_b0 and KoreaPeter/deepclip_b5. The Hub code imports deepclip, so install it together with transformers:

pip install "deepclip[detect]" transformers
from transformers import pipeline

# 🖼 Image classification
clf = pipeline(
    "image-classification",
    model="KoreaPeter/deepclip_b0",  # or KoreaPeter/deepclip_b5
    trust_remote_code=True,
)
result = clf("face.jpg")
# [{'label': 'fake', 'score': 0.9712}, {'label': 'real', 'score': 0.0288}]

result = clf("face.jpg", return_artifacts=True)
# [..., {'artifacts': {'face': {'blur': 0.12, ...}, 'eyes': {...}, 'nose': {...}, 'mouth': {...}}}]

# 🎬 Video classification
clf = pipeline(
    "video-classification",
    model="KoreaPeter/deepclip_b0",
    trust_remote_code=True,
)
result = clf("video.mp4", num_frames=20, agg_mode="conf", return_artifacts=True)
# [{'label': 'fake', 'score': 0.9634}, {'label': 'real', 'score': 0.0366}, {'artifacts': {...}}]
Argument Pipeline Description
margin_ratio, conf_thres, min_face_ratio, tta_hflip both Same as Option B
return_artifacts both Append the 20 artifact scores (mean over the frames for videos)
num_frames, agg_mode video Same as Option B
return_frame_scores video Append the fake probability of every sampled frame

When no face is found, both pipelines return [{'label': 'no_face_detected', 'score': -1.0}].

Option B: Pip

pip install "deepclip[detect]"

The detect extra installs ultralytics for the YOLO face detection used by deepclip.detect. If you only need the models (timm.create_model("deepclip_b0", pretrained=True)), pip install deepclip is enough.

Predict DeepFake Image

from deepclip.detect import ClipImagePredictor

# Initialize the predictor
predictor = ClipImagePredictor(
            margin_ratio = 0.2, # Margin ratio around the detected face crop
            conf_thres = 0.5, # Confidence threshold for face detection
            min_face_ratio = 0.01, # Minimum face-to-frame size ratio to process
            model_name = "deepclip_b0", # deepclip_b0, deepclip_b5
            )

# Fake probability only
prob = predictor.predict_img(
            img_path = "path/to/image.jpg",
            tta_hflip = 0.0 # Horizontal Flip for Test-Time Augmentation
            )
print(f"Deepfake Probability: {prob:.4f}")

# Fake probability + artifact scores
result = predictor.predict_img_artifacts(img_path = "path/to/image.jpg")
print(result["prob"])                       # fake probability
print(result["artifacts"]["mouth"]["blend"]) # blending artifacts on the mouth

Predict DeepFake Video

from deepclip.detect import ClipVideoPredictor

# Initialize the predictor
predictor = ClipVideoPredictor(
            margin_ratio = 0.2, # Margin ratio around the detected face crop
            conf_thres = 0.5, # Confidence threshold for face detection
            min_face_ratio = 0.01, # Minimum face-to-frame size ratio to process
            model_name = "deepclip_b0", # deepclip_b0, deepclip_b5
            )

# Fake probability only
prob = predictor.predict_video(
            video_path = "path/to/video.mp4",
            num_frames = 20, # Number of frames to sample per video
            agg_mode = "conf", # Aggregation Method: 'conf', 'mean', 'vote'
            tta_hflip = 0.0 # Horizontal Flip for Test-Time Augmentation
            )
print(f"Deepfake Probability: {prob:.4f}")

# Fake probability + artifact scores (mean over the frames)
result = predictor.predict_video_artifacts(video_path = "path/to/video.mp4", num_frames = 20)

Output of predict_*_artifacts

{
    "prob": 0.9634,               # fake probability (aggregated with agg_mode for videos)
    "artifacts": {                # None when no face is found (prob is 0.5)
        "face":  {"blur": 0.12, "color": 0.08, "texture": 0.21, "structure": 0.05, "blend": 0.64},
        "eyes":  {...},
        "nose":  {...},
        "mouth": {...},
    },
}
agg_mode Frame Aggregation
conf Mean of the confident frames (> 0.8 or < 0.2) when enough frames agree, otherwise mean
mean Mean of all frames
vote Ratio of frames with probability > 0.5

🐳 Building Docker Image

Build from the repository root (GPU, or CPU with --build-arg BASE_IMAGE=python:3.11-slim):

docker build -f preprocess/Dockerfile -t deepclip-preprocess:gpu .

Or pull the prebuilt image from Docker Hub (gpu / cpu):

docker pull seoyunje/deepclip-preprocess:gpu

🏃 Running Docker

docker run --gpus all --shm-size=8g --rm -v <DATA_ROOT>:/data -v deepclip-cache:/root/.cache/deepclip -it seoyunje/deepclip-preprocess:gpu

<DATA_ROOT> holds the FF++ videos and csv/FF++_Metadata.csv. The weights are downloaded to the deepclip-cache volume on the first run. Set STEPS (e.g. -e STEPS=3,4,5) to run only some steps, and *_ARGS to override a step's arguments (see preprocess/README.md).

🗂️ Data Preparation

Download the FaceForensics++ (c23) videos and csv files from Kaggle into DATA_ROOT. The pipeline runs 5 steps, writing every output to DATA_ROOT:

  1. split_data - train / test metadata
  2. detect_original_face - YOLO face boxes of the real videos, reused for their fakes (pixel-aligned pairs)
  3. crop_face - face crops of the real and fake videos
  4. generate_landmark - dlib 68 landmarks of the fake crops
  5. raw_annotation - SSIM forgery masks, forged regions and artifact flags (raw_annotation.parquet, pair_label)

Without Docker, run each step with python -m preprocess.<step> --root-dir DATA_ROOT after pip install -r preprocess/requirements.txt. Details in preprocess/README.md.

🚀 Training

train_deepclip.py and test_deepclip.py run against the full repo, not the pip package. Clone it and install the full dev environment:

git clone https://github.com/SEOYUNJE/DeepClip.git
cd DeepClip
pip install -r requirements.txt

DeepClip is trained on the frame-level FaceForensics++ dataset with its forgery annotation. We recommend Weights & Biases (W&B) for experiment tracking (--wandb-api-key is required).

!python train_deepclip.py \
    --root-dir DATA_ROOT \
    --model-name "deepclip_b0" \ # deepclip_b0, deepclip_b5, deepclip_b0_v2, deepclip_b5_v2
    --output-dir "checkpoints" \ # Directory of the best checkpoint
    --seed 2025 \ # for reproducibility
    --wandb-api-key "your-api-key" # Write your own api key

DATA_ROOT must contain the frame metadata and the face crops:

DATA_ROOT/
├── crops/
│   └── {vid}/
│       ├── 12.png
│       └── ...
└── train_clip_frame_metadata.csv   # vid, frame_idx, label (REAL/FAKE), ori_vid, pair_label

pair_label is a string of 20 0/1 characters, one per (region, type) pair in the order face-blur, face-color, ..., mouth-blend (index = 5 × region + type).

Argument Default Description
--root-dir (required) Root directory of the dataset
--model-name deepclip_b0 deepclip_b0, deepclip_b5, deepclip_b0_v2 or deepclip_b5_v2
--config deepclip/config/{model_name}.yaml Training recipe (model, LoRA, text sampling, loss, optimizer)
--output-dir . Directory of the best checkpoint
--seed 2025 Random seed
--num-workers cpu_count - 1 DataLoader workers
--debug off Train on a small subset
--wandb-api-key (required) W&B API key
--metadata train_clip_frame_metadata.csv Metadata file under --root-dir
--crop-dir crops Face crop directory under --root-dir

📈 Model Evaluation

test_deepclip.py evaluates a pretrained DeepClip model on deepfake videos and prints AUC, accuracy, log loss, macro F1, the confusion matrix and per-class precision / recall / F1. Run it from the cloned repo (see 🚀 Training).

!python test_deepclip.py \
    --root-dir DATA_ROOT \
    --dataset "celeb_df_v2" \ # celeb_df_v2, ff++, kodf
    --model-name "deepclip_b0" \ # deepclip_b0, deepclip_b5
    --margin-ratio 0.2 \
    --conf-thres 0.5 \
    --min-face-ratio 0.01 \
    --num-frames 20 \
    --agg-mode "conf" \ # conf, mean, vote
    --tta-hflip 0.0 \
    --top-k 3 # Number of top artifact scores used by the rule-based fake probability (1-20)

The final fake probability of a video is rule-based: max(prob, S_art), where S_art is the sigmoid of the mean of the top-k artifact logits. Artifacts can only raise the fake probability, never lower it.

Both models are trained on FaceForensics++ only.

In-Domain Evaluation

Tested on the FaceForensics++ test set.

Model Test@AUC Test@Accuracy Test@Log Loss Test@Macro F1
⚡ deepclip_b0 0.9917 96.33% 0.0959 0.9396
🔥 deepclip_b5 0.9935 98.08% 0.0739 0.9672

Cross-Domain Evaluation

Tested on datasets not seen during training.

Celeb-DF (v2)

Model Test@AUC Test@Accuracy Test@Log Loss Test@Macro F1
⚡ deepclip_b0 0.6821 61.97% 0.8823 0.6147
🔥 deepclip_b5 0.7674 74.13% 0.7455 0.7162

KoDF

Model Test@AUC Test@Accuracy Test@Log Loss Test@Macro F1
⚡ deepclip_b0 0.7726 68.83% 1.5238 0.6791
🔥 deepclip_b5 0.8277 71.75% 1.6868 0.7072

⚖️ License

This project is licensed under the terms of the MIT license.

Metadata

Release files for deepclip 1.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for deepclip 1.2.0
File Size Uploaded Provenance Actions
deepclip-1.2.0.tar.gz 1.4 MB With provenance Details for deepclip-1.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for deepclip 1.2.0
File Interpreter ABI Platform Actions
deepclip-1.2.0-py3-none-any.whl Python 3 none any Details for deepclip-1.2.0-py3-none-any.whl

Total release size: 2.8 MB

Release files / deepclip-1.2.0.tar.gz

Download URL deepclip-1.2.0.tar.gz
Size 1.4 MB
Tags Source
SHA-256 checksum
How to use checksums
11c3b1907a0266b14e019dbbeff760038e196dd8f29b92f4ae8630d65974dd97
BLAKE2b-256 checksum
How to use checksums
6967199c9a07016b7a579d38cc778eb7ae2864c8aedf7afcdd74f8daa313dd25
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Release files / deepclip-1.2.0-py3-none-any.whl

Download URL deepclip-1.2.0-py3-none-any.whl
Size 1.4 MB
Tags Python 3
SHA-256 checksum
How to use checksums
41b8b95b892e23282af916c8fd42e5fbd912305dc30e51309ac15d36cdcca664
BLAKE2b-256 checksum
How to use checksums
28beca1239b8a38813ec6506b57049a12afb6008f66a620d3c8f97d63ec66421
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Security for deepclip 1.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for deepclip-1.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page