Skip to content
mever-teamPublic

About

A Python framework for reliably assessing synthetic image detection methods

Resources

Stars

50 stars

Watchers

4 watching

Forks

Latest commit

Β 

History

45 Commits

Folders and files

Repository files navigation

SIDBench: A Synthetic Image Detection Benchmark

This project is a framework for benchmarking several state-of-the-art synthetic image detection models.

News

✨ 12/3/2024 Integrate DeFake model

Setup

Install dependecies

Create a new environment named pytorch_env:

conda create --name pytorch_env python=3.11
conda activate pytorch_env

and then install pytorch dependecies

conda install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia

Note ✨: This framework has been tested with Python version 3.11.7 and PyTorch 2.1.2. However, it should work with other versions as well. Please ensure that your PyTorch version is greater than 2.0. ⚠️

Install additional dependencies:

pip install -r requirements.txt

To run the Dire model, mpi4py is required. You can install it using Conda with the following command:

conda install -c conda-forge mpi4py mpich

Integrated Models

The following models have been integrated. Note that for some of these models, there are multiple pretrained instances, trained on different images generated by various generative models such as ProGAN, StyleGAN, and Latent Diffusion, etc.

Model Name Paper Title Original Code
CNNDetect CNN-generated images are surprisingly easy to spot...for now πŸ”—
DIMD On the detection of synthetic images generated by diffusion models. πŸ”—
FreqDetect Leveraging Frequency Analysis for Deep Fake Image Recognition πŸ”—
Fusing Fusing global and local features for generalized AI-synthesized image detection πŸ”—
GramNet Global Texture Enhancement for Fake Face Detection In the Wild πŸ”—
LGrad Learning on Gradients: Generalized Artifacts Representation for GAN-Generated Images Detection πŸ”—
Dire DIRE for Diffusion-Generated Image Detection πŸ”—
UnivFD Towards Universal Fake Image Detectors that Generalize Across Generative Models πŸ”—
NPR Rethinking the Up-Sampling Operations in CNN-based Generative Network for Generalizable Deepfake Detection πŸ”—
PatchCraft PatchCraft: Exploring Texture Patch for Efficient AI-generated Image Detection πŸ”—
DeFake DE-FAKE: Detection and Attribution of Fake Images Generated by Text-to-Image Generation Models πŸ”—
Rine Leveraging Representations from Intermediate Encoder-blocks for Synthetic Image Detection πŸ”—

Usage

Run model on multiple images

To run the model on a directory containing images, use the following command:

python test.py --dataPath <root_path_to_images>

This command executes the model using the default selection, which is UnivFD. If you wish to use a different model, you can specify it using the --modelName flag. For example, to use the CNNDetect model, the command would be:

python test.py --dataPath <root_path_to_images> --modelName=CNNDetect

The models supported by this framework are listed in the table above. When selecting a model using the --modelName flag, ensure you use one of the valid names as specified below. These names correspond to the models' implementations and must be used exactly as shown to ensure proper function invocation:

VALID_MODELS = ['CNNDetect', 'FreqDetect', 'Fusing', 'GramNet', 'LGrad', 'UnivFD', 'PatchCraft', 'Rine', 'DIMD', 'NPR', 'Dire', 'DeFake']

You need also to define the path to the pretrained weights with the --ckpt flag. Ensure you replace <path_to_pretrained_weights> with the actual file path to your pretrained model weights.

python test.py --dataPath <root_path_to_images> --modelName=CNNDetect --ckpt <path_to_pretrained_weights>

Replace <root_path_to_images> with the actual path to your directory of images, and <path_to_pretrained_weights> with the path to the pretrained weights file.

You can download the pretrained weights from dkarageo/sidbench on Hugging Face. Run the following in the root of this repository to place them under ./weights:

hf download dkarageo/sidbench --local-dir weights

hf is provided by huggingface_hub (pip install -U "huggingface_hub[cli]"). The full set is 8.74 GB; the model card lists per-file sizes and how to download a subset.

Model Name Pretrained Weights File Name Trained On
CNNDetect weights/cnndetect/blur_jpg_prob0.1.pth proGAN augmented (recompressed) with 10% probability
weights/cnndetect/blur_jpg_prob0.5.pth proGAN augmented (recompressed) with 50% probability
DIMD weights/dimd/corvi22_latent_model.pth Latent Diffusion
weights/dimd/corvi22_progan_model.pth proGAN
weights/dimd/gandetection_resnet50nodown_progan.pth proGAN images
weights/dimd/gandetection_resnet50nodown_stylegan2.pth styleGAN2 images
Dire weights/dire/lsun_adm.pth adm (diffusion)
weights/dire/lsun_iddpm.pth iddpm (Denoising diffusion probabilistic model)
weights/dire/lsun_pndm.pth pndm (Pseudo Numerical Methods for Diffusion Models)
weights/dire/lsun_stylegan.pth stylegan
FreqDetect weights/freqdetect/DCTAnalysis.pth
UnivFD weights/univfd/fc_weights.pth proGAN
Fusing weights/fusing/PSM.pth
GramNet weights/gramnet/Gram.pth
LGrad weights/lgrad/LGrad.pth proGAN
weights/lgrad/LGrad-1class-Trainon-Progan_horse.pth proGAN with one class images
weights/lgrad/LGrad-2class-Trainon-Progan_chair_horse.pth proGAN with two class images
weights/lgrad/LGrad-4class-Trainon-Progan_car_cat_chair_horse.pth proGAN with four class images
NPR weights/npr/NPR.pth
DeFake weights/defake/clip_linear.pth hybrid detector (image + text) tranined in diffusion images
Rine weights/rine/model_1class_trainable.pth proGAN with one class images
weights/rine/model_2class_trainable.pth proGAN with two class images
weights/rine/model_4class_trainable.pth proGAN with four class images
weights/rine/model_ldm_trainable.pth latent diffusion with one class images
PatchCraft weights/rptc/RPTC.pth proGAN

Some models require additional parameters to be defined.

FreqDetect requires two additional files, which are to be specified by the flags --dctMean and --dctVar. By default, these are set to ./weights/freqdetect/dct_mean.zip and ./weights/freqdetect/dct_var.zip, respectively. If you have downloaded the weights directory and placed it in the root directory of the framework, these parameters can remain unchanged.

LGrad requires the initialization of a StyleGAN discriminator, which is used to extract image gradients serving as image features. To specify the path to the pretrained discriminator, use the flag --LGradGenerativeModelPath. The default pretrained weights are provided in the file karras2019stylegan-bedrooms-256x256_discriminator.pth, located within the ./weights/preprocessing directory.

Dire requires the initialization of a diffusion generative model that extracts image features. To specify the path to the pretrained discriminator, use the flag --DireGenerativeModelPath. The default pretrained weights are provided in the file lsun_bedroom.pt, located within the ./weights/preprocessing directory.

DeFake requires the initialization of a fine-tuned CLIP encoder (--defakeClipEncoderPath=./weights/defake/finetune_clip.pt) and a BLIP decoder for the generation of images captions (--defakeBlipPath=./weights/defake/model_base_capfilt_large.pth).

Saving the predictions

To save the predictions, specify an output file using the --predictionsFile flag. For example:

python test.py --dataPath <root_path_to_images> --predictionsFile <path_to_output_file>

Additional parameters for input preprocessing

To resize images, use the --loadSize flag followed by the desired dimension. If no resize size is specified, the default behavior is to apply no resizing. For example, to resize images to 256x256 pixels, you would use:

--loadSize=256

Important Note on Resizing: The impact of resizing on the results cannot be overstated. For certain models, resizing can significantly improve outcomes, while for others, it may detract from performance. This effect is closely tied to the original resolution of the input images. Specifically, in the case of high-resolution images, resizing becomes a crucial factor to consider. For a deeper insight into how resizing affects model performance, please refer to the Evaluation Section.

To crop images, utilize the --cropSize flag similarly. The default crop size is set to 224 pixels, meaning if no crop size is specified, images will be cropped to 224x224 pixels by default. For example, to crop images to 256x256 pixels, the correct flag is:

--cropSize=256

⚠️ Important Note: For models such as UnivFD and Rine, which are based on CLIP, the input size must be set to 224x224 pixels due to CLIP's specific input size requirements. Therefore, use --loadSize=224 for these models.

Evaluate on a dataset

You can run evaluations and save the results by executing the following command:

python evaluate.py --modelName=UnivFD --ckpt=./weights/univfd/fc_weights.pth --resultFolder=results/

This command uses the UnivFD model with its corresponding pretrained weights located at ./weights/univfd/fc_weights.pth, and saves the results in the results/ folder.

You can utilize the same list of models and pretrained weights, adjusting the --modelName and --ckpt flags as needed. Similarly, you can modify the behavior for cropping and resizing according to your requirements.

In addition, you can use the following flags to further process the images:

--jpegQuality: Applies JPEG recompression with the defined quality level e.g. 95, 90, 50, ... --gaussianSigma: Applies Gaussian blurring with the defined sigma value e.g. 1,2,4.

These flags allow for additional image transformation during evaluation, potentially influencing the model's performance based on your specific experimental setup.

Input for evaluation

There are four ways to tell evaluate.py and benchmark.py where the images are:

Option Give it Results
--dataRoot a dataset folder with one subfolder per generator, each containing 0_real and 1_fake folders one row per generator
--dataPath a folder containing 0_real and 1_fake folders one row
--realPath and --fakePath any folder of real images and any folder of fake images one row
a datasets list in a config file several folders, each in any of the layouts above one row per entry

--dataRoot is the easiest way to evaluate a published dataset. For example, the wang2020 test set unzips to:

CNN_synth_testset/
β”œβ”€β”€ biggan/0_real, biggan/1_fake
β”œβ”€β”€ progan/airplane/0_real, progan/airplane/1_fake, progan/bicycle/...
└── ...
python evaluate.py --dataRoot /path/to/CNN_synth_testset --source wang2020

Each subfolder (biggan, progan, ...) is scored separately and labelled with its name. The 0_real and 1_fake folders can be nested at any depth inside it, as in progan. Folders whose names start with a dot are skipped.

--dataPath treats everything under the folder as one dataset: images with 0_real in their path below the folder are real, and images with 1_fake are fake. 0_real and 1_fake count as a whole folder name, or as a part of a file name set off by _, - or ., e.g. img_7_0_real.png or 0_real_34.png. They don't count when attached to other letters or digits, so img_10_real.png (where the 0 belongs to 10) is not labelled real by accident.

--realPath and --fakePath take any two folders: every image under --realPath is real and every image under --fakePath is fake, whatever the folders and files are called. If one of them uses the 0_real/1_fake naming, only the images named that way are used from it (the real folder's 0_real images, the fake folder's 1_fake images), so you can also point both at folders laid out for --dataPath. If both are the same folder, it works like --dataPath.

Images are searched in all subfolders. Files ending in .png, .jpg, .jpeg or .bmp, in any upper or lower case, are used.

Before any model is loaded, the script prints how many real and fake images it found for each dataset, with notes about images it found but did not use (e.g. using 100 of 1000 images, only those named 0_real). It then stops with a list of every problem it found: missing folders, datasets without real or without fake images, images that count as both, and a real folder holding images named 1_fake but none named 0_real (or the reverse), which usually means the two folders were swapped.

Where results are saved

evaluate.py saves its results in <resultFolder>/<dataset name>/<modelName>/<settings>/, for example results/wang2020/UnivFD/crop_224_resize_256/ (benchmark.py adds the trainedOn folder before the model name). The dataset name is the source (see below): --source if given, otherwise the folder's name for --dataRoot and --dataPath, otherwise unnamed. When one run covers several sources, such as a datasets list mixing wang2020 and my_data entries, each source gets its own folder.

Existing results are never deleted silently: if a folder the run would write already contains results, the script stops before loading the model and lists the folders. Use another --resultFolder or --source, or add --overwrite (or overwrite: true in a config file) to replace them. benchmark.py checks every folder of the whole run before it starts.

Both scripts print all their options when they start, so a saved log shows how the run was made. Each results folder also gets a config.yaml with the options of that result: the model, checkpoint, preprocessing, degradation and datasets. It is a config file, so python evaluate.py --config <results folder>/config.yaml --resultFolder <another folder> runs the same evaluation again.

Labels saved with the results

Every result row is saved in metrics.json with three labels, used by the scripts in scripts/ to average and plot results:

  • generative_model: what made the fake images, e.g. biggan. With --dataRoot, the subfolder's name; otherwise set with --generativeModel.
  • source: the dataset the images come from, e.g. wang2020, which also names the results folder. With --dataRoot or --dataPath, it defaults to the folder's name, and --source replaces it. With --realPath/--fakePath, set it with --source, otherwise it is unnamed. With a datasets list, each entry has its own, and --source instead runs only the entries with that source.
  • family: the type of generator, e.g. gan or diffusion, so results can be averaged per type. If it is not given (with --family or in a datasets entry), it is looked up by the generator's name in configs/families.yaml, which lists the generators of each family; generators not listed get unknown. Add your own generators there.

Run a benchmark

benchmark.py evaluates several models on several datasets, first on the clean images and then under JPEG compression and Gaussian blur:

python benchmark.py --config configs/benchmark.yaml

The config file lists the datasets, the models with their pretrained weights, and the degradations to apply. Results are saved under <resultFolder>/<dataset name>/<trainedOn>/<modelName>/, so different checkpoints of the same model are kept apart. Without a config file, the script uses the models listed in models/models.py; give the data with --dataRoot, --dataPath, or --realPath and --fakePath, as described in Input for evaluation.

Use a configuration file

As an alternative to command-line flags, test.py, evaluate.py and benchmark.py can read their options from a YAML file given with --config. Commented examples are in configs/:

python test.py --config configs/test.yaml
python evaluate.py --config configs/evaluate.yaml

The keys are the command-line flag names, e.g. modelName, ckpt, dataPath and batchSize. Flags given on the command line override the values in the file, which in turn override the defaults:

python evaluate.py --config configs/evaluate.yaml --gpus -1   # same settings, but on the CPU

Unknown keys and values of the wrong type stop the script with an error, so typos are not silently ignored. Relative paths are relative to the folder you run the command from.

For evaluate.py and benchmark.py, the data options dataRoot, dataPath, realPath and fakePath can be set in the file like any other option. If any data option is given on the command line, all data options in the file, including the datasets list, are ignored, so --dataRoot on the command line works even if the file sets dataPath. If more than one data option is still set, the first one in this order is used and the script says which ones it ignored: realPath with fakePath, dataPath, dataRoot, the datasets list.

To combine datasets laid out differently, such as one folder of real photos shared by several generators, list them in the file instead:

datasets:
  - real_path: /path/to/wang2020/biggan        # contains 0_real and 1_fake
    fake_path: /path/to/wang2020/biggan
    source: wang2020
    generative_model: biggan
  - real_path: /path/to/real_photos            # any folder of real images
    fake_path: /path/to/sdxl_images            # any folder of fake images
    source: my_data
    family: diffusion
    generative_model: stable-diffusion-xl

real_path and fake_path are required and follow the same rules as --realPath and --fakePath. family is looked up in configs/families.yaml when not given.

Citation

If you use our framework in your research, please cite our paper:

Schinas, M., & Papadopoulos, S. (2024). SIDBench: A Python Framework for Reliably Assessing Synthetic Image Detection Methods. MAD ?24, June 10, 2024, Phuket, Thailand. arXiv preprint arXiv:2404.18552.

Contact

Manos Schinas (manosetro@iti.gr)

Symeon (Akis) Papadopoulos (papadop@iti.gr)

About

A Python framework for reliably assessing synthetic image detection methods

Resources

Stars

50 stars

Watchers

4 watching

Forks

Releases

Packages

Used by

Contributors

Languages