shunliwang commited on
Commit
8bc3305
·
1 Parent(s): 2e0a93e
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -35
  2. README.md +271 -3
  3. preprocessing/config.yaml +52 -0
  4. preprocessing/dataset2lmdb_test.py +99 -0
  5. preprocessing/dataset_json/Celeb-DF-v2.json +3 -0
  6. preprocessing/dataset_json/DF40_all.json +3 -0
  7. preprocessing/dataset_json/DFDC.json +3 -0
  8. preprocessing/dataset_json/DFDCP.json +3 -0
  9. preprocessing/dataset_json/DeepFakeDetection.json +3 -0
  10. preprocessing/dataset_json/DiffFace.json +3 -0
  11. preprocessing/dataset_json/DreamBooth.json +3 -0
  12. preprocessing/dataset_json/FF-DF.json +3 -0
  13. preprocessing/dataset_json/FF-F2F.json +3 -0
  14. preprocessing/dataset_json/FF-FS.json +3 -0
  15. preprocessing/dataset_json/FF-NT.json +3 -0
  16. preprocessing/dataset_json/FaceForensics++.json +3 -0
  17. preprocessing/dataset_json/FaceShifter.json +3 -0
  18. preprocessing/dataset_json/GPT4o.json +3 -0
  19. preprocessing/dataset_json/HPS.json +3 -0
  20. preprocessing/dataset_json/Hart.json +3 -0
  21. preprocessing/dataset_json/Imagic.json +3 -0
  22. preprocessing/dataset_json/Infinity.json +3 -0
  23. preprocessing/dataset_json/LoRA.json +3 -0
  24. preprocessing/dataset_json/MidJourney.json +3 -0
  25. preprocessing/dataset_json/Midjourney_diff.json +3 -0
  26. preprocessing/dataset_json/SRI.json +3 -0
  27. preprocessing/dataset_json/SRI_hq.json +3 -0
  28. preprocessing/dataset_json/abstract_dataset.py +668 -0
  29. preprocessing/dataset_json/gpa.json +3 -0
  30. preprocessing/dataset_json/heygen.json +3 -0
  31. preprocessing/dataset_json/others/Chameleon.json +3 -0
  32. preprocessing/dataset_json/others/CoDiff.json +3 -0
  33. preprocessing/dataset_json/others/CollabDiff.json +3 -0
  34. preprocessing/dataset_json/others/DCFace.json +3 -0
  35. preprocessing/dataset_json/others/DeeperForensics-1.0.json +3 -0
  36. preprocessing/dataset_json/others/DiT_cdf.json +3 -0
  37. preprocessing/dataset_json/others/DiT_ff.json +3 -0
  38. preprocessing/dataset_json/others/EFSAll_cdf.json +3 -0
  39. preprocessing/dataset_json/others/EFSAll_ff.json +3 -0
  40. preprocessing/dataset_json/others/FRAll_cdf.json +3 -0
  41. preprocessing/dataset_json/others/FRAll_ff.json +3 -0
  42. preprocessing/dataset_json/others/FSAll_cdf.json +3 -0
  43. preprocessing/dataset_json/others/FSAll_ff.json +3 -0
  44. preprocessing/dataset_json/others/FaceForensics++_vae.json +3 -0
  45. preprocessing/dataset_json/others/FreeDoM_I.json +3 -0
  46. preprocessing/dataset_json/others/FreeDoM_T.json +3 -0
  47. preprocessing/dataset_json/others/MRAA_cdf.json +3 -0
  48. preprocessing/dataset_json/others/MRAA_ff.json +3 -0
  49. preprocessing/dataset_json/others/SDXL.json +3 -0
  50. preprocessing/dataset_json/others/SDXL_Refine.json +3 -0
.gitattributes CHANGED
@@ -1,35 +1,2 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.json filter=lfs diff=lfs merge=lfs -text
2
+ *.dat filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,3 +1,271 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DFG - Deepfake Genome Codebase
2
+
3
+ ## 1. Environment Setup
4
+
5
+ Create and activate the conda environment:
6
+
7
+ ```bash
8
+ # Create a new conda environment (Python 3.10 recommended)
9
+ conda create -n dfg python=3.10 -y
10
+
11
+ # Activate the environment
12
+ conda activate dfg
13
+
14
+ # Install dependencies
15
+ pip install -r requirements.txt
16
+ ```
17
+
18
+ ## 2. Dataset Configuration
19
+
20
+ Before training or testing, you need to update the **dataset global path** to match your actual data location.
21
+
22
+ Open `training/dataset/abstract_dataset.py` and modify the `DATASET_GLOBAL_PATH` variable:
23
+
24
+ ```python
25
+ # Change this to your actual dataset root path
26
+ DATASET_GLOBAL_PATH = "/your/actual/dataset/path/"
27
+ ```
28
+
29
+ This path should point to the root directory containing your deepfake detection datasets (e.g., `DeepFakeGenome`, `deepfake_detecton_dataset`, etc.).
30
+
31
+ ## 3. Project and Dataset Structure
32
+
33
+ ```
34
+ DFG/
35
+ ├── preprocessing/
36
+ │ └── dataset_json/ # Dataset index JSON files
37
+ │ ├── protocol_2_train.json
38
+ │ ├── protocol_2_test.json
39
+ │ ├── protocol_3_test.json
40
+ │ ├── protocol_4_test.json
41
+ │ └── ...
42
+ ├── training/
43
+ │ ├── config/
44
+ │ │ └── detector/ # Detector config YAML files
45
+ │ ├── detectors/ # Detector implementations
46
+ │ │ ├── __init__.py # Register all detectors here
47
+ │ │ ├── base_detector.py
48
+ │ │ └── ...
49
+ │ ├── networks/ # Backbone network implementations
50
+ │ ├── loss/ # Loss function definitions
51
+ │ ├── metrics/ # Evaluation metrics
52
+ │ ├── train.py # Training entry point
53
+ │ └── test_pall.py # Testing entry point
54
+ ├── train.sh # Training script examples
55
+ ├── test.sh # Testing script examples
56
+ ├── requirements.txt # Python dependencies
57
+ └── README.md
58
+ ```
59
+
60
+ ## 4. Training
61
+
62
+ Refer to `train.sh` for all training commands. Example:
63
+
64
+ ```bash
65
+ python -m torch.distributed.launch --master_port=29503 --nproc_per_node=8 training/train.py \
66
+ --detector_path ./training/config/detector/clip_large_fft.yaml \
67
+ --no-save_feat --ddp
68
+ ```
69
+
70
+ Key arguments:
71
+ - `--master_port`: port for distributed training (change if port conflicts occur)
72
+ - `--nproc_per_node`: number of GPUs
73
+ - `--detector_path`: path to the detector config YAML
74
+ - `--no-save_feat`: disable feature saving during training
75
+ - `--ddp`: enable DistributedDataParallel
76
+
77
+ ## 5. Testing
78
+
79
+ Refer to `test.sh` for all testing commands. Example:
80
+
81
+ ```bash
82
+ # Test on protocol 2 & 3
83
+ python -m torch.distributed.launch --master_port=29510 --nproc_per_node=8 training/test_pall.py --ddp \
84
+ --test_dataset "protocol_2_test" "protocol_3_test" \
85
+ --detector_path ./training/config/detector/clip_large_fft.yaml \
86
+ --weights_path logs/clip_models/clip_large_fft_2025-11-08-13-56-51
87
+
88
+ # Test on protocol 4
89
+ python -m torch.distributed.launch --master_port=29512 --nproc_per_node=8 training/test_pall.py --ddp \
90
+ --test_dataset "protocol_4_test" \
91
+ --detector_path ./training/config/detector/clip_large_fft.yaml \
92
+ --weights_path logs/clip_models/clip_large_fft_2025-11-08-13-56-51 \
93
+ --test_config test_config_p4.yaml
94
+ ```
95
+
96
+ Key arguments:
97
+ - `--test_dataset`: one or more dataset names (must match JSON filenames under `preprocessing/dataset_json/`)
98
+ - `--weights_path`: path to trained model checkpoint directory
99
+ - `--test_config`: additional test configuration (required for protocol 4)
100
+
101
+ ## 6. Adding a Custom Detector
102
+
103
+ To integrate your own detector into the framework, follow these three steps:
104
+
105
+ ### Step 1: Create the detector config YAML
106
+
107
+ Create a new file under `training/config/detector/`, e.g., `my_detector.yaml`:
108
+
109
+ ```yaml
110
+ # log dir
111
+ log_dir: logs/my_detector
112
+
113
+ # model setting
114
+ pretrained: null
115
+ model_name: my_detector
116
+ backbone_name: resnet34
117
+
118
+ # backbone setting
119
+ backbone_config:
120
+ mode: original
121
+ num_classes: 2
122
+ inc: 3
123
+ dropout: false
124
+
125
+ # dataset
126
+ all_dataset: [FaceForensics++, FF-F2F, FF-DF, FF-FS, FF-NT, FaceShifter, DeepFakeDetection, Celeb-DF-v1, Celeb-DF-v2, DFDCP, DFDC, DeeperForensics-1.0, UADFV]
127
+ train_dataset: [protocol_2_train]
128
+ test_dataset: [protocol_2_test]
129
+
130
+ compression: c23
131
+ train_batchSize: 64
132
+ test_batchSize: 64
133
+ workers: 8
134
+ frame_num: {'train': 16, 'test': 16}
135
+ resolution: 224
136
+ with_mask: false
137
+ with_landmark: false
138
+
139
+ # data augmentation
140
+ use_data_augmentation: false
141
+ data_aug:
142
+ flip_prob: 0.5
143
+ rotate_prob: 0.5
144
+ rotate_limit: [-10, 10]
145
+ blur_prob: 0.5
146
+ blur_limit: [3, 7]
147
+ brightness_prob: 0.5
148
+ brightness_limit: [-0.1, 0.1]
149
+ contrast_limit: [-0.1, 0.1]
150
+ quality_lower: 40
151
+ quality_upper: 100
152
+
153
+ # mean and std for normalization
154
+ mean: [0.485, 0.456, 0.406]
155
+ std: [0.229, 0.224, 0.225]
156
+
157
+ # optimizer config
158
+ optimizer:
159
+ type: adam
160
+ adam:
161
+ lr: 0.0002
162
+ beta1: 0.9
163
+ beta2: 0.999
164
+ eps: 0.00000001
165
+ weight_decay: 0.0005
166
+ amsgrad: false
167
+
168
+ # training config
169
+ lr_scheduler: null
170
+ nEpochs: 20
171
+ start_epoch: 0
172
+ save_epoch: 1
173
+ rec_iter: 100
174
+ logdir: ./logs
175
+ manualSeed: 1024
176
+ save_ckpt: true
177
+ save_feat: true
178
+
179
+ # loss function
180
+ loss_func: cross_entropy
181
+ losstype: null
182
+
183
+ # metric
184
+ metric_scoring: auc
185
+
186
+ # cuda
187
+ ngpu: 1
188
+ cuda: true
189
+ cudnn: true
190
+
191
+ save_avg: true
192
+ save_latest_ckpt: true
193
+ ```
194
+
195
+ ### Step 2: Create the detector Python file
196
+
197
+ Create `training/detectors/my_detector.py`:
198
+
199
+ ```python
200
+ import torch
201
+ import torch.nn as nn
202
+
203
+ from metrics.base_metrics_class import calculate_metrics_for_train
204
+ from .base_detector import AbstractDetector
205
+ from detectors import DETECTOR
206
+ from networks import BACKBONE
207
+ from loss import LOSSFUNC
208
+
209
+
210
+ @DETECTOR.register_module(module_name='my_detector')
211
+ class MyDetector(AbstractDetector):
212
+ def __init__(self, config):
213
+ super().__init__()
214
+ self.config = config
215
+ self.backbone = self.build_backbone(config)
216
+ self.loss_func = LOSSFUNC[config['loss_func']]()
217
+
218
+ def build_backbone(self, config):
219
+ backbone = BACKBONE[config['backbone_name']](config['backbone_config'])
220
+ return backbone
221
+
222
+ def features(self, data_dict: dict) -> torch.Tensor:
223
+ return self.backbone(data_dict['image'])
224
+
225
+ def classifier(self, features: torch.Tensor) -> torch.Tensor:
226
+ return self.fc(features)
227
+
228
+ def get_losses(self, data_dict: dict, pred_dict: dict) -> dict:
229
+ label = data_dict['label']
230
+ pred = pred_dict['cls']
231
+ loss = self.loss_func(pred, label)
232
+ return {'overall': loss}
233
+
234
+ def get_train_metrics(self, data_dict: dict, pred_dict: dict) -> dict:
235
+ label = data_dict['label']
236
+ pred = pred_dict['cls']
237
+ auc, eer, acc, ap = calculate_metrics_for_train(label.detach(), pred.detach())
238
+ return {'acc': acc, 'auc': auc, 'eer': eer, 'ap': ap}
239
+
240
+ def forward(self, data_dict: dict, inference=False) -> dict:
241
+ features = self.features(data_dict)
242
+ pred = self.classifier(features)
243
+ prob = torch.softmax(pred, dim=1)[:, 1]
244
+ pred_dict = {'cls': pred, 'prob': prob, 'feat': features}
245
+ return pred_dict
246
+ ```
247
+
248
+ ### Step 3: Register the detector in `__init__.py`
249
+
250
+ Add the following import line to `training/detectors/__init__.py`:
251
+
252
+ ```python
253
+ from .my_detector import MyDetector
254
+ ```
255
+
256
+ That's it! Now you can train and test with your custom detector:
257
+
258
+ ```bash
259
+ # Train
260
+ python -m torch.distributed.launch --master_port=29503 --nproc_per_node=8 training/train.py \
261
+ --detector_path ./training/config/detector/my_detector.yaml \
262
+ --no-save_feat --ddp
263
+
264
+ # Test
265
+ python -m torch.distributed.launch --master_port=29510 --nproc_per_node=8 training/test_pall.py --ddp \
266
+ --test_dataset "protocol_2_test" "protocol_3_test" \
267
+ --detector_path ./training/config/detector/my_detector.yaml \
268
+ --weights_path logs/my_detector/<your_checkpoint_folder>
269
+ ```
270
+
271
+
preprocessing/config.yaml ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ preprocess:
2
+ dataset_name: # the name of dataset
3
+ choices: ['FaceForensics++','Celeb-DF-v1', 'Celeb-DF-v2', 'DFDCP', 'DFDC', 'DeeperForensics-1.0','UADFV']
4
+ default: 'FaceForensics++'
5
+ dataset_root_path: # the root path to the dataset
6
+ type: str
7
+ default: 'F:\'
8
+ comp: # the compression level of videos, only in the dataset of FaceForensics++.
9
+ choices: ['raw', 'c23', 'c40']
10
+ default: 'c23'
11
+ mode: # based on the numbers of frame or skip the specific stride of frames.
12
+ choices: ['fixed_num_frames', 'fixed_stride']
13
+ default: 'fixed_num_frames'
14
+ stride: # when 'mode' is 'fixed_stride', 'stride' is the number of frames to skip between each frame extracted.
15
+ type: int
16
+ default: 10
17
+ num_frames: # when 'mode' is 'fixed_num_frames', 'num_frames' is the number of frames to extract from each video.
18
+ type: int
19
+ default: 32
20
+
21
+ rearrange:
22
+ dataset_name: # the name of dataset
23
+ choices: ['FaceForensics++', 'DeepFakeDetection', 'Celeb-DF-v1', 'Celeb-DF-v2','DFDCP', 'DFDC', 'DeeperForensics-1.0','UADFV','FaceShifter']
24
+ default: 'FaceForensics++'
25
+ dataset_root_path: # the root path to the dataset
26
+ type: str
27
+ default: ''
28
+ output_file_path: # the json path to the dataset
29
+ type: str
30
+ default: '../preprocessing/dataset_json_v6'
31
+ comp: # the compression level of videos, only in the dataset of FaceForensics++.
32
+ choices: ['raw', 'c23', 'c40']
33
+ default: 'c23'
34
+ perturbation: # Extensive real-world perturbations are applied to DeeperForensics-1.0 dataset
35
+ choices: ['end_to_end','end_to_end_level_1','end_to_end_level_2','end_to_end_level_3','end_to_end_level_4',
36
+ 'end_to_end_level_5','end_to_end_mix_2_distortions','end_to_end_mix_3_distortions',
37
+ 'end_to_end_mix_4_distortions','end_to_end_random_level','reenact_postprocess']
38
+ default: 'end_to_end'
39
+
40
+ to_lmdb:
41
+ dataset_name: # the name of dataset
42
+ choices: ['FaceForensics++', 'DeepFakeDetection', 'Celeb-DF-v1', 'Celeb-DF-v2','DFDCP', 'DFDC', 'DeeperForensics-1.0','UADFV','FaceShifter']
43
+ default: 'FaceForensics++'
44
+ dataset_root_path: # the root path to the dataset
45
+ type: str
46
+ default: './datasets_v2'
47
+ output_lmdb_dir: # the json path to the dataset
48
+ type: str
49
+ default: './datasets_lmdbs'
50
+ comp: # the compression level of videos, only in the dataset of FaceForensics++.
51
+ choices: ['raw', 'c23', 'c40']
52
+ default: 'c23'
preprocessing/dataset2lmdb_test.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import cv2
4
+ import lmdb
5
+ import yaml
6
+ from PIL import Image
7
+ import io
8
+ import numpy as np
9
+ def file_to_binary(file_path):
10
+ """convert to binary"""
11
+ if file_path.endswith('.npy'):
12
+ data = np.load(file_path)
13
+ file_binary = data.tobytes()
14
+ else:
15
+ with open(file_path, 'rb') as f:
16
+ file_binary = f.read()
17
+ return file_binary
18
+
19
+
20
+ def create_lmdb_dataset(source_folder, lmdb_path, dataset_name, map_size):
21
+ """create LMDB dataset"""
22
+ # open LMDB file,create dataset
23
+ db = lmdb.open(lmdb_path, map_size=map_size)
24
+ with db.begin(write=True) as txn:
25
+
26
+ for root, dirs, files in os.walk(source_folder,followlinks=True):
27
+ print(root)
28
+ if 'video' in root:
29
+ continue
30
+ for file in files:
31
+ print(file)
32
+ image_path = os.path.join(root, file)
33
+ #
34
+ relative_path = f"{dataset_name}/" + os.path.relpath(image_path, source_folder)
35
+ print("relative_path:", relative_path)
36
+ key = relative_path.encode('utf-8')
37
+ # txn.delete(key)
38
+ # relative_path = f"{dataset_name}\\original_sequences" + os.path.relpath(image_path, source_folder)
39
+ # key = relative_path.encode('utf-8')
40
+ print("image_path:", image_path)
41
+ value = file_to_binary(image_path)
42
+
43
+ # write dataset
44
+ txn.put(key, value)
45
+
46
+
47
+
48
+ db.close()
49
+
50
+
51
+ def read_lmdb(lmdb_dir_path):
52
+ # validate the key and value in the generated LMDB
53
+ env = lmdb.open(lmdb_dir_path)
54
+
55
+ idx = '%09d' % 5
56
+ with env.begin(write=False) as txn:
57
+ # key for validation
58
+ key='npy_test\\000_003\\000.npy'
59
+ binary = txn.get(key.encode())
60
+ data = np.frombuffer(binary, dtype=np.uint32).reshape((81, 2))
61
+
62
+ # image_buf = np.frombuffer(image_bin, dtype=np.uint8)
63
+ # img = cv2.imdecode(image_buf, cv2.IMREAD_COLOR)
64
+ # image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
65
+
66
+
67
+ # Usage example
68
+ import argparse
69
+ # Create the ArgumentParser object
70
+ parser = argparse.ArgumentParser(description='Process some inputs.')
71
+
72
+ # Add the --dataset_size argument
73
+ parser.add_argument('--dataset_size', type=int, default=25, required=True,
74
+ help='lmdb requires pre-specifying the total dataset size (GB)')
75
+
76
+ # Parse the arguments
77
+ args = parser.parse_args()
78
+
79
+ if __name__ == '__main__':
80
+ # from config.yaml load parameters
81
+ yaml_path = './config_DFo.yaml'
82
+ # open the yaml file
83
+ try:
84
+ with open(yaml_path, 'r') as f:
85
+ config = yaml.safe_load(f)
86
+ except yaml.parser.ParserError as e:
87
+ print("YAML file parsing error:", e)
88
+
89
+ config=config['to_lmdb']
90
+ dataset_name = config['dataset_name']['default']
91
+ dataset_size = args.dataset_size
92
+ dataset_root_path = config['dataset_root_path']['default']
93
+ output_lmdb_dir =config['output_lmdb_dir']['default']
94
+ os.makedirs(output_lmdb_dir,exist_ok=True)
95
+
96
+ dataset_dir_path = f"{dataset_root_path}/{dataset_name}"
97
+ lmdb_path=f"{output_lmdb_dir}/{dataset_name}_lmdb"
98
+ create_lmdb_dataset(dataset_dir_path, lmdb_path, dataset_name,map_size=int(dataset_size) * 1024 * 1024 * 1024)
99
+ #read_lmdb(lmdb_path)
preprocessing/dataset_json/Celeb-DF-v2.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:113fcde0ea7b1a03caf63e2ed2f3e6d80bf99efe18073ca05c606c9d0b260804
3
+ size 20076776
preprocessing/dataset_json/DF40_all.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6308d04ffd0e9da59a7df058bf6a27ae41da0a15f03add8a11f694f510a5b2f6
3
+ size 125339450
preprocessing/dataset_json/DFDC.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8d1184758620c71b68ad8715e068644ed9792bdc6b2feba9cf0b7f8a98a7e00d
3
+ size 44499938
preprocessing/dataset_json/DFDCP.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ed5022e36380b3c1ca21941e95bad7bcf08fc3c58e50441012757189eed1868d
3
+ size 27634090
preprocessing/dataset_json/DeepFakeDetection.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aed7e4a257feb622435119bec621dc09b0614823e4e3e1186bc4b280a394fa90
3
+ size 45849312
preprocessing/dataset_json/DiffFace.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f3c8ff3368ae4c6ae5950ccc79d63603279c0c103264d2215eebd270e6a7535f
3
+ size 7177344
preprocessing/dataset_json/DreamBooth.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2e4cbfa4d0efef6f4b9f8fec1ad4be9efdad7def115bf993e1684c631b1bedbc
3
+ size 7841108
preprocessing/dataset_json/FF-DF.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:be532fe67b2bebaaaf3a81237ccc518ba8ded043564b187c923e7c6e79bc242b
3
+ size 6633592
preprocessing/dataset_json/FF-F2F.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0cb9c3e9e209dfd45390b7da7a882fcefab4af4a53bd672c999b594dda49cee3
3
+ size 6647968
preprocessing/dataset_json/FF-FS.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3f14cc304d80e39597d280234c654aca1fb5af3615a26b3c431e662cb50e2c23
3
+ size 6615423
preprocessing/dataset_json/FF-NT.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:112494833ab34ab6b9476dc2632aed5c5928961b004e7267f3690c8b70b1c947
3
+ size 6804515
preprocessing/dataset_json/FaceForensics++.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:18802f85a0de861d07140fafe4fbbdda67167afb110d0b6f5cece1738c7428c8
3
+ size 17184826
preprocessing/dataset_json/FaceShifter.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f2031400f8aea5369ebad30c5b9839db370c1bf7f7ba16183a9f9ed833b30904
3
+ size 6695159
preprocessing/dataset_json/GPT4o.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6d5c880684793cc10837cb5b39e2e19cdf5c0ab460f8cb6f4214fe0f65ef8571
3
+ size 247155
preprocessing/dataset_json/HPS.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8334f78d11be167a14492562af36dc45e11899d6d9e6949e51a5c8d252e8c89b
3
+ size 8968435
preprocessing/dataset_json/Hart.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f69d96d5d5aed7be81ad805e113c6128d1965b275a9586ff704d72abcdd2df50
3
+ size 4182208
preprocessing/dataset_json/Imagic.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8bcfb6a163b2c9e41d9c9444208a99cd04abfa634c209604348518cad56ad3eb
3
+ size 7937325
preprocessing/dataset_json/Infinity.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5cd859f6e5aa9fdcb2e18bcc3a095c0ef73d9355fc3d083255291b186bbe7bbe
3
+ size 4332314
preprocessing/dataset_json/LoRA.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc22024e17c872fda7beb88c09007e2c7a78b78255248a7f58e98ba58ee58517
3
+ size 7655888
preprocessing/dataset_json/MidJourney.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f9e087f7d7525fdfe756a017cc5f4b88b8ea8056954f5f5b2bbec5c99192c8b
3
+ size 767342
preprocessing/dataset_json/Midjourney_diff.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c3238e3ba309dc523560756611ae404ebf3d21084211fe05064452a38b5cf6c8
3
+ size 8330096
preprocessing/dataset_json/SRI.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6b750334121350c9c4f2e5790b1917400c26fd4af4323aec185415985993afe7
3
+ size 1307793
preprocessing/dataset_json/SRI_hq.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d1f4d7b697768c8a37d4409cbd8fc2c11c3d54a37697007c79bc6830c6965a6d
3
+ size 1206968
preprocessing/dataset_json/abstract_dataset.py ADDED
@@ -0,0 +1,668 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # author: Zhiyuan Yan
2
+ # email: zhiyuanyan@link.cuhk.edu.cn
3
+ # date: 2023-03-30
4
+ # description: Abstract Base Class for all types of deepfake datasets.
5
+
6
+ import sys
7
+
8
+ import lmdb
9
+
10
+ sys.path.append('.')
11
+
12
+ import os
13
+ import math
14
+ import yaml
15
+ import glob
16
+ import json
17
+
18
+ import numpy as np
19
+ from copy import deepcopy
20
+ import cv2
21
+ import random
22
+ from PIL import Image
23
+ from collections import defaultdict
24
+
25
+ import torch
26
+ from torch.autograd import Variable
27
+ from torch.utils import data
28
+ from torchvision import transforms as T
29
+
30
+ import albumentations as A
31
+
32
+ from .albu import IsotropicResize
33
+
34
+ FFpp_pool=['FaceForensics++','FaceShifter','DeepFakeDetection','FF-DF','FF-F2F','FF-FS','FF-NT']#
35
+ import pdb
36
+
37
+ def all_in_pool(inputs,pool):
38
+ for each in inputs:
39
+ if each not in pool:
40
+ return False
41
+ return True
42
+
43
+
44
+ class DeepfakeAbstractBaseDataset(data.Dataset):
45
+ """
46
+ Abstract base class for all deepfake datasets.
47
+ """
48
+ def __init__(self, config=None, mode='train'):
49
+ """Initializes the dataset object.
50
+
51
+ Args:
52
+ config (dict): A dictionary containing configuration parameters.
53
+ mode (str): A string indicating the mode (train or test).
54
+
55
+ Raises:
56
+ NotImplementedError: If mode is not train or test.
57
+ """
58
+
59
+ # Set the configuration and mode
60
+ self.config = config
61
+ self.mode = mode
62
+ self.compression = config['compression']
63
+ self.frame_num = config['frame_num'][mode] #
64
+
65
+ # Check if 'video_mode' exists in config, otherwise set video_level to False
66
+ self.video_level = config.get('video_mode', False)
67
+ self.clip_size = config.get('clip_size', None)
68
+ self.lmdb = config.get('lmdb', False)
69
+ # Dataset dictionary
70
+ self.image_list = []
71
+ self.label_list = []
72
+
73
+ # Set the dataset dictionary based on the mode
74
+ if mode == 'train':
75
+ dataset_list = config['train_dataset']
76
+
77
+ # Training data should be collected together for training
78
+ image_list, label_list = [], []
79
+ for one_data in dataset_list:
80
+ # if one_data == "ivy_fake_train":
81
+ # tmp_image, tmp_label, tmp_name = self.collect_img_and_label_for_one_dataset(one_data)
82
+ # tmp_image = list(tmp_image)
83
+ # tmp_label = list(tmp_label)
84
+ # sample_indices = random.sample(range(len(tmp_image)), 9510)
85
+ # tmp_image = [tmp_image[i] for i in sample_indices]
86
+ # tmp_label = [tmp_label[i] for i in sample_indices]
87
+
88
+
89
+ # if one_data == "FF-DF":
90
+ # tmp_image, tmp_label, tmp_name = self.collect_img_and_label_for_one_dataset(one_data)
91
+ # tmp_image = list(tmp_image)
92
+ # tmp_label = list(tmp_label)
93
+ # # print('ffdf')
94
+
95
+ # sample_indices = random.sample(range(len(tmp_image)), 7937)
96
+ # tmp_image = [tmp_image[i] for i in sample_indices]
97
+ # tmp_label = [tmp_label[i] for i in sample_indices]
98
+ tmp_image, tmp_label, tmp_name = self.collect_img_and_label_for_one_dataset(one_data)
99
+ image_list.extend(tmp_image)
100
+ label_list.extend(tmp_label)
101
+ if self.lmdb:
102
+ if len(dataset_list)>1:
103
+ if all_in_pool(dataset_list,FFpp_pool):
104
+ lmdb_path = os.path.join(config['lmdb_dir'], f"FaceForensics++_lmdb")
105
+ self.env = lmdb.open(lmdb_path, create=False, subdir=True, readonly=True, lock=False)
106
+ else:
107
+ raise ValueError('Training with multiple dataset and lmdb is not implemented yet.')
108
+ else:
109
+ lmdb_path = os.path.join(config['lmdb_dir'], f"{dataset_list[0] if dataset_list[0] not in FFpp_pool else 'FaceForensics++'}_lmdb")
110
+ self.env = lmdb.open(lmdb_path, create=False, subdir=True, readonly=True, lock=False)
111
+ elif mode == 'test':
112
+ one_data = config['test_dataset']
113
+ # Test dataset should be evaluated separately. So collect only one dataset each time
114
+ image_list, label_list, name_list = self.collect_img_and_label_for_one_dataset(one_data)
115
+ if self.lmdb:
116
+ lmdb_path = os.path.join(config['lmdb_dir'], f"{one_data}_lmdb" if one_data not in FFpp_pool else 'FaceForensics++_lmdb')
117
+ self.env = lmdb.open(lmdb_path, create=False, subdir=True, readonly=True, lock=False)
118
+ else:
119
+ raise NotImplementedError('Only train and test modes are supported.')
120
+
121
+ assert len(image_list)!=0 and len(label_list)!=0, f"Collect nothing for {mode} mode!"
122
+ self.image_list, self.label_list = image_list, label_list
123
+
124
+
125
+ # Create a dictionary containing the image and label lists
126
+ self.data_dict = {
127
+ 'image': self.image_list,
128
+ 'label': self.label_list,
129
+ }
130
+
131
+ self.transform = self.init_data_aug_method()
132
+
133
+ def init_data_aug_method(self):
134
+ # trans = A.Compose([
135
+ # A.HorizontalFlip(p=self.config['data_aug']['flip_prob']),
136
+ # A.Rotate(limit=self.config['data_aug']['rotate_limit'], p=self.config['data_aug']['rotate_prob']),
137
+ # A.GaussianBlur(blur_limit=self.config['data_aug']['blur_limit'], p=self.config['data_aug']['blur_prob']),
138
+ # A.OneOf([
139
+ # IsotropicResize(max_side=self.config['resolution'], interpolation_down=cv2.INTER_AREA, interpolation_up=cv2.INTER_CUBIC),
140
+ # IsotropicResize(max_side=self.config['resolution'], interpolation_down=cv2.INTER_AREA, interpolation_up=cv2.INTER_LINEAR),
141
+ # IsotropicResize(max_side=self.config['resolution'], interpolation_down=cv2.INTER_LINEAR, interpolation_up=cv2.INTER_LINEAR),
142
+ # ], p = 0 if self.config['with_landmark'] else 1),
143
+ # A.OneOf([
144
+ # A.RandomBrightnessContrast(brightness_limit=self.config['data_aug']['brightness_limit'], contrast_limit=self.config['data_aug']['contrast_limit']),
145
+ # A.FancyPCA(),
146
+ # A.HueSaturationValue()
147
+ # ], p=0.5),
148
+ # A.ImageCompression(quality_lower=self.config['data_aug']['quality_lower'], quality_upper=self.config['data_aug']['quality_upper'], p=0.5)
149
+ # ],
150
+ # keypoint_params=A.KeypointParams(format='xy') if self.config['with_landmark'] else None
151
+ # )
152
+
153
+ # video no aug
154
+ trans = A.Compose([
155
+ A.HorizontalFlip(p=0.5),
156
+ A.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.2, p=0.5),
157
+ A.HueSaturationValue(p=0.3),
158
+ A.ImageCompression(quality_lower=40, quality_upper=100, p=0.1), # compression: 40-100, p=0.1
159
+ A.GaussNoise(p=0.1),
160
+ A.MotionBlur(p=0.1),
161
+ A.CLAHE(p=0.1),
162
+ A.ChannelShuffle(p=0.1),
163
+ A.Cutout(p=0.1),
164
+ A.RandomGamma(p=0.3),
165
+ A.GlassBlur(p=0.3),
166
+ ])
167
+
168
+ return trans
169
+
170
+ def rescale_landmarks(self, landmarks, original_size=256, new_size=224):
171
+ scale_factor = new_size / original_size
172
+ rescaled_landmarks = landmarks * scale_factor
173
+ return rescaled_landmarks
174
+
175
+
176
+ def collect_img_and_label_for_one_dataset(self, dataset_name: str):
177
+ """Collects image and label lists.
178
+
179
+ Args:
180
+ dataset_name (str): A list containing one dataset information. e.g., 'FF-F2F'
181
+
182
+ Returns:
183
+ list: A list of image paths.
184
+ list: A list of labels.
185
+
186
+ Raises:
187
+ ValueError: If image paths or labels are not found.
188
+ NotImplementedError: If the dataset is not implemented yet.
189
+ """
190
+ # Initialize the label and frame path lists
191
+ label_list = []
192
+ frame_path_list = []
193
+
194
+ # Record video name for video-level metrics
195
+ video_name_list = []
196
+
197
+ # Try to get the dataset information from the JSON file
198
+ if not os.path.exists(self.config['dataset_json_folder']):
199
+ self.config['dataset_json_folder'] = self.config['dataset_json_folder'].replace('/Youtu_Pangu_Security_Public', '/Youtu_Pangu_Security/public')
200
+ try:
201
+ with open(os.path.join(self.config['dataset_json_folder'], dataset_name + '.json'), 'r') as f:
202
+ dataset_info = json.load(f)
203
+ except Exception as e:
204
+ print(e)
205
+ raise ValueError(f'dataset {dataset_name} not exist!')
206
+
207
+ # If JSON file exists, do the following data collection
208
+ # FIXME: ugly, need to be modified here.
209
+ cp = None
210
+ if dataset_name == 'FaceForensics++_c40':
211
+ dataset_name = 'FaceForensics++'
212
+ cp = 'c40'
213
+ elif dataset_name == 'FF-DF_c40':
214
+ dataset_name = 'FF-DF'
215
+ cp = 'c40'
216
+ elif dataset_name == 'FF-F2F_c40':
217
+ dataset_name = 'FF-F2F'
218
+ cp = 'c40'
219
+ elif dataset_name == 'FF-FS_c40':
220
+ dataset_name = 'FF-FS'
221
+ cp = 'c40'
222
+ elif dataset_name == 'FF-NT_c40':
223
+ dataset_name = 'FF-NT'
224
+ cp = 'c40'
225
+ # Get the information for the current dataset
226
+ for label in dataset_info[dataset_name]:
227
+ sub_dataset_info = dataset_info[dataset_name][label][self.mode]
228
+ # Special case for FaceForensics++ and DeepFakeDetection, choose the compression type
229
+ # NOTE
230
+ if cp == None and dataset_name in ['FF-DF', 'FF-F2F', 'FF-FS', 'FF-NT', 'FaceForensics++','DeepFakeDetection','FaceShifter','ivy_fake_train','ivy_fake_test',
231
+ 'ivy_fake_test_Deepfakes','ivy_fake_test_NeuralTextures','ivy_fake_test_FaceSwap','ivy_fake_test_Face2Face']:
232
+ sub_dataset_info = sub_dataset_info[self.compression]
233
+ elif cp == 'c40' and dataset_name in ['FF-DF', 'FF-F2F', 'FF-FS', 'FF-NT', 'FaceForensics++','DeepFakeDetection','FaceShifter']:
234
+ sub_dataset_info = sub_dataset_info['c40']
235
+
236
+ # Iterate over the videos in the dataset
237
+
238
+ for video_name, video_info in sub_dataset_info.items():
239
+ # Unique video name
240
+
241
+ unique_video_name = video_info['label'] + '_' + video_name
242
+
243
+ # Get the label and frame paths for the current video
244
+ if video_info['label'] not in self.config['label_dict']:
245
+ raise ValueError(f'Label {video_info["label"]} is not found in the configuration file.')
246
+ label = self.config['label_dict'][video_info['label']]
247
+ frame_paths = video_info['frames']
248
+ # sorted video path to the lists
249
+ if '\\' in frame_paths[0]:
250
+ frame_paths = sorted(frame_paths, key=lambda x: int(x.split('\\')[-1].split('.')[0]))
251
+ else:
252
+ frame_paths = sorted(frame_paths, key=lambda x: int(x.split('/')[-1].split('.')[0]))
253
+
254
+ # Consider the case when the actual number of frames (e.g., 270) is larger than the specified (i.e., self.frame_num=32)
255
+ # In this case, we select self.frame_num frames from the original 270 frames
256
+ total_frames = len(frame_paths)
257
+ if self.frame_num < total_frames:
258
+ total_frames = self.frame_num
259
+ if self.video_level:
260
+ # Select clip_size continuous frames
261
+ start_frame = random.randint(0, total_frames - self.frame_num) if self.mode == 'train' else 0
262
+ frame_paths = frame_paths[start_frame:start_frame + self.frame_num] # update total_frames
263
+ else:
264
+ # Select self.frame_num frames evenly distributed throughout the video
265
+ step = total_frames // self.frame_num
266
+ frame_paths = [frame_paths[i] for i in range(0, total_frames, step)][:self.frame_num]
267
+
268
+ # If video-level methods, crop clips from the selected frames if needed
269
+ if self.video_level:
270
+ if self.clip_size is None:
271
+ raise ValueError('clip_size must be specified when video_level is True.')
272
+ # Check if the number of total frames is greater than or equal to clip_size
273
+ if total_frames >= self.clip_size:
274
+ # Initialize an empty list to store the selected continuous frames
275
+ selected_clips = []
276
+
277
+ # Calculate the number of clips to select
278
+ num_clips = total_frames // self.clip_size
279
+
280
+ if num_clips > 1:
281
+ # Calculate the step size between each clip
282
+ clip_step = (total_frames - self.clip_size) // (num_clips - 1)
283
+
284
+ # Select clip_size continuous frames from each part of the video
285
+ for i in range(num_clips):
286
+ # Ensure start_frame + self.clip_size - 1 does not exceed the index of the last frame
287
+ start_frame = random.randrange(i * clip_step, min((i + 1) * clip_step, total_frames - self.clip_size + 1)) if self.mode == 'train' else i * clip_step
288
+ continuous_frames = frame_paths[start_frame:start_frame + self.clip_size]
289
+ assert len(continuous_frames) == self.clip_size, 'clip_size is not equal to the length of frame_path_list'
290
+ selected_clips.append(continuous_frames)
291
+
292
+ else:
293
+ start_frame = random.randrange(0, total_frames - self.clip_size + 1) if self.mode == 'train' else 0
294
+ continuous_frames = frame_paths[start_frame:start_frame + self.clip_size]
295
+ assert len(continuous_frames)==self.clip_size, 'clip_size is not equal to the length of frame_path_list'
296
+ selected_clips.append(continuous_frames)
297
+
298
+ # Append the list of selected clips and append the label
299
+ label_list.extend([label] * len(selected_clips))
300
+ frame_path_list.extend(selected_clips)
301
+ # video name save
302
+ video_name_list.extend([unique_video_name] * len(selected_clips))
303
+
304
+ else:
305
+ print(f"Skipping video {unique_video_name} because it has less than clip_size ({self.clip_size}) frames ({total_frames}).")
306
+
307
+ # Otherwise, extend the label and frame paths to the lists according to the number of frames
308
+ else:
309
+ # Extend the label and frame paths to the lists according to the number of frames
310
+ label_list.extend([label] * total_frames)
311
+ frame_path_list.extend(frame_paths)
312
+ # video name save
313
+ video_name_list.extend([unique_video_name] * len(frame_paths))
314
+
315
+ # Shuffle the label and frame path lists in the same order
316
+ shuffled = list(zip(label_list, frame_path_list, video_name_list))
317
+ random.shuffle(shuffled)
318
+ label_list, frame_path_list, video_name_list = zip(*shuffled)
319
+
320
+ return frame_path_list, label_list, video_name_list
321
+
322
+
323
+ def load_rgb(self, file_path):
324
+ """
325
+ Load an RGB image from a file path and resize it to a specified resolution.
326
+
327
+ Args:
328
+ file_path: A string indicating the path to the image file.
329
+
330
+ Returns:
331
+ An Image object containing the loaded and resized image.
332
+
333
+ Raises:
334
+ ValueError: If the loaded image is None.
335
+ """
336
+ size = self.config['resolution'] # if self.mode == "train" else self.config['resolution']
337
+ if not self.lmdb:
338
+ # if not file_path[0] == '.':
339
+ # file_path = f'./{self.config["rgb_dir"]}\\'+file_path
340
+ if not os.path.exists(file_path):
341
+ file_path = file_path.replace('\\', '/')
342
+ assert os.path.exists(file_path), f"{file_path} does not exist"
343
+ img = cv2.imread(file_path)
344
+ if img is None:
345
+ raise ValueError('Loaded image is None: {}'.format(file_path))
346
+ elif self.lmdb:
347
+ with self.env.begin(write=False) as txn:
348
+ # transfer the path format from rgb-path to lmdb-key
349
+ if file_path[0]=='.':
350
+ file_path=file_path.replace('./datasets\\','')
351
+
352
+ image_bin = txn.get(file_path.encode())
353
+ image_buf = np.frombuffer(image_bin, dtype=np.uint8)
354
+ img = cv2.imdecode(image_buf, cv2.IMREAD_COLOR)
355
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
356
+ img = cv2.resize(img, (size, size), interpolation=cv2.INTER_CUBIC)
357
+ return Image.fromarray(np.array(img, dtype=np.uint8))
358
+
359
+
360
+ def load_mask(self, file_path):
361
+ """
362
+ Load a binary mask image from a file path and resize it to a specified resolution.
363
+
364
+ Args:
365
+ file_path: A string indicating the path to the mask file.
366
+
367
+ Returns:
368
+ A numpy array containing the loaded and resized mask.
369
+
370
+ Raises:
371
+ None.
372
+ """
373
+ size = self.config['resolution']
374
+ if file_path is None:
375
+ return np.zeros((size, size, 1))
376
+ if not self.lmdb:
377
+ # if not file_path[0] == '.':
378
+ # file_path = f'./{self.config["rgb_dir"]}\\'+file_path
379
+ if os.path.exists(file_path):
380
+ mask = cv2.imread(file_path, 0)
381
+ if mask is None:
382
+ mask = np.zeros((size, size))
383
+ else:
384
+ return np.zeros((size, size, 1))
385
+ else:
386
+ with self.env.begin(write=False) as txn:
387
+ # transfer the path format from rgb-path to lmdb-key
388
+ if file_path[0]=='.':
389
+ file_path=file_path.replace('./datasets\\','')
390
+
391
+ image_bin = txn.get(file_path.encode())
392
+ if image_bin is None:
393
+ mask = np.zeros((size, size,3))
394
+ else:
395
+ image_buf = np.frombuffer(image_bin, dtype=np.uint8)
396
+ mask = cv2.imdecode(image_buf, cv2.IMREAD_COLOR)
397
+ mask = cv2.resize(mask, (size, size)) / 255
398
+ mask = np.expand_dims(mask, axis=2)
399
+ return np.float32(mask)
400
+
401
+ def load_landmark(self, file_path):
402
+ """
403
+ Load 2D facial landmarks from a file path.
404
+
405
+ Args:
406
+ file_path: A string indicating the path to the landmark file.
407
+
408
+ Returns:
409
+ A numpy array containing the loaded landmarks.
410
+
411
+ Raises:
412
+ None.
413
+ """
414
+ if file_path is None:
415
+ return np.zeros((81, 2))
416
+ if not self.lmdb:
417
+ # if not file_path[0] == '.':
418
+ # file_path = f'./{self.config["rgb_dir"]}\\'+file_path
419
+ if os.path.exists(file_path):
420
+ landmark = np.load(file_path)
421
+ else:
422
+ return np.zeros((81, 2))
423
+ else:
424
+ with self.env.begin(write=False) as txn:
425
+ # transfer the path format from rgb-path to lmdb-key
426
+ if file_path[0]=='.':
427
+ file_path=file_path.replace('./datasets\\','')
428
+ binary = txn.get(file_path.encode())
429
+ landmark = np.frombuffer(binary, dtype=np.uint32).reshape((81, 2))
430
+ landmark=self.rescale_landmarks(np.float32(landmark), original_size=256, new_size=self.config['resolution'])
431
+ return landmark
432
+
433
+ def to_tensor(self, img):
434
+ """
435
+ Convert an image to a PyTorch tensor.
436
+ """
437
+ return T.ToTensor()(img)
438
+
439
+ def normalize(self, img):
440
+ """
441
+ Normalize an image.
442
+ """
443
+ mean = self.config['mean']
444
+ std = self.config['std']
445
+ normalize = T.Normalize(mean=mean, std=std)
446
+ return normalize(img)
447
+
448
+ def data_aug(self, img, landmark=None, mask=None, augmentation_seed=None):
449
+ """
450
+ Apply data augmentation to an image, landmark, and mask.
451
+
452
+ Args:
453
+ img: An Image object containing the image to be augmented.
454
+ landmark: A numpy array containing the 2D facial landmarks to be augmented.
455
+ mask: A numpy array containing the binary mask to be augmented.
456
+
457
+ Returns:
458
+ The augmented image, landmark, and mask.
459
+ """
460
+
461
+ # Set the seed for the random number generator
462
+ if augmentation_seed is not None:
463
+ random.seed(augmentation_seed)
464
+ np.random.seed(augmentation_seed)
465
+
466
+ # Create a dictionary of arguments
467
+ kwargs = {'image': img}
468
+
469
+ # Check if the landmark and mask are not None
470
+ if landmark is not None:
471
+ kwargs['keypoints'] = landmark
472
+ kwargs['keypoint_params'] = A.KeypointParams(format='xy')
473
+ if mask is not None:
474
+ mask = mask.squeeze(2)
475
+ if mask.max() > 0:
476
+ kwargs['mask'] = mask
477
+
478
+ # Apply data augmentation
479
+ transformed = self.transform(**kwargs)
480
+
481
+ # Get the augmented image, landmark, and mask
482
+ # NOTE
483
+ # augmented_img = transformed['image']
484
+ augmented_img = kwargs['image']
485
+ augmented_landmark = transformed.get('keypoints')
486
+ augmented_mask = transformed.get('mask',mask)
487
+
488
+ # Convert the augmented landmark to a numpy array
489
+ if augmented_landmark is not None:
490
+ augmented_landmark = np.array(augmented_landmark)
491
+
492
+ # Reset the seeds to ensure different transformations for different videos
493
+ if augmentation_seed is not None:
494
+ random.seed()
495
+ np.random.seed()
496
+
497
+ return augmented_img, augmented_landmark, augmented_mask
498
+
499
+ def __getitem__(self, index, no_norm=False):
500
+ """
501
+ Returns the data point at the given index.
502
+
503
+ Args:
504
+ index (int): The index of the data point.
505
+
506
+ Returns:
507
+ A tuple containing the image tensor, the label tensor, the landmark tensor,
508
+ and the mask tensor.
509
+ """
510
+ # Get the image paths and label
511
+ image_paths = self.data_dict['image'][index]
512
+ label = self.data_dict['label'][index]
513
+
514
+ # Image-level: FaceForensics++\manipulated_sequences\NeuralTextures\c23\frames\487_477\000.png
515
+ # Video-level: image_paths ['FaceForensics++\\original_sequences\\youtube\\c23\\frames\\977\\000.png', ..., 'FaceForensics++\\original_sequences\\youtube\\c23\\frames\\977\\314.png']
516
+ if not isinstance(image_paths, list):
517
+ image_paths = [image_paths] # for the image-level IO, only one frame is used
518
+
519
+ image_tensors = []
520
+ landmark_tensors = []
521
+ mask_tensors = []
522
+ augmentation_seed = None
523
+
524
+ for image_path in image_paths:
525
+ # Initialize a new seed for data augmentation at the start of each video
526
+ if self.video_level and image_path == image_paths[0]:
527
+ augmentation_seed = random.randint(0, 2**32 - 1)
528
+
529
+ # Get the mask and landmark paths
530
+ mask_path = image_path.replace('frames', 'masks') # Use .png for mask
531
+ landmark_path = image_path.replace('frames', 'landmarks').replace('.png', '.npy') # Use .npy for landmark
532
+
533
+ # Load the image
534
+ try:
535
+ image = self.load_rgb(image_path)
536
+ except Exception as e:
537
+ # Skip this image and return the first one
538
+ print(f"Error loading image at index {index}: {e}")
539
+ return self.__getitem__(0)
540
+ image = np.array(image) # Convert to numpy array for data augmentation
541
+
542
+ # Load mask and landmark (if needed)
543
+ if self.config['with_mask']:
544
+ mask = self.load_mask(mask_path)
545
+ else:
546
+ mask = None
547
+ if self.config['with_landmark']:
548
+ landmarks = self.load_landmark(landmark_path)
549
+ else:
550
+ landmarks = None
551
+
552
+ # Do Data Augmentation
553
+ if self.mode == 'train' and self.config['use_data_augmentation']:
554
+ image_trans, landmarks_trans, mask_trans = self.data_aug(image, landmarks, mask, augmentation_seed)
555
+ else:
556
+ # if self.mode == 'train':
557
+ # print("Train w/o data_augmentation")
558
+ image_trans, landmarks_trans, mask_trans = deepcopy(image), deepcopy(landmarks), deepcopy(mask)
559
+
560
+
561
+ # To tensor and normalize
562
+ if not no_norm:
563
+ image_trans = self.normalize(self.to_tensor(image_trans))
564
+ if self.config['with_landmark']:
565
+ landmarks_trans = torch.from_numpy(landmarks)
566
+ if self.config['with_mask']:
567
+ mask_trans = torch.from_numpy(mask_trans)
568
+
569
+ image_tensors.append(image_trans)
570
+ landmark_tensors.append(landmarks_trans)
571
+ mask_tensors.append(mask_trans)
572
+
573
+ if self.video_level:
574
+ # Stack image tensors along a new dimension (time)
575
+ image_tensors = torch.stack(image_tensors, dim=0)
576
+ # Stack landmark and mask tensors along a new dimension (time)
577
+ if not any(landmark is None or (isinstance(landmark, list) and None in landmark) for landmark in landmark_tensors):
578
+ landmark_tensors = torch.stack(landmark_tensors, dim=0)
579
+ if not any(m is None or (isinstance(m, list) and None in m) for m in mask_tensors):
580
+ mask_tensors = torch.stack(mask_tensors, dim=0)
581
+ else:
582
+ # Get the first image tensor
583
+ image_tensors = image_tensors[0]
584
+ # Get the first landmark and mask tensors
585
+ if not any(landmark is None or (isinstance(landmark, list) and None in landmark) for landmark in landmark_tensors):
586
+ landmark_tensors = landmark_tensors[0]
587
+ if not any(m is None or (isinstance(m, list) and None in m) for m in mask_tensors):
588
+ mask_tensors = mask_tensors[0]
589
+
590
+ return image_tensors, label, landmark_tensors, mask_tensors
591
+
592
+ @staticmethod
593
+ def collate_fn(batch):
594
+ """
595
+ Collate a batch of data points.
596
+
597
+ Args:
598
+ batch (list): A list of tuples containing the image tensor, the label tensor,
599
+ the landmark tensor, and the mask tensor.
600
+
601
+ Returns:
602
+ A tuple containing the image tensor, the label tensor, the landmark tensor,
603
+ and the mask tensor.
604
+ """
605
+ # Separate the image, label, landmark, and mask tensors
606
+ images, labels, landmarks, masks = zip(*batch)
607
+
608
+ # Stack the image, label, landmark, and mask tensors
609
+ images = torch.stack(images, dim=0)
610
+ labels = torch.LongTensor(labels)
611
+
612
+ # Special case for landmarks and masks if they are None
613
+ if not any(landmark is None or (isinstance(landmark, list) and None in landmark) for landmark in landmarks):
614
+ landmarks = torch.stack(landmarks, dim=0)
615
+ else:
616
+ landmarks = None
617
+
618
+ if not any(m is None or (isinstance(m, list) and None in m) for m in masks):
619
+ masks = torch.stack(masks, dim=0)
620
+ else:
621
+ masks = None
622
+
623
+ # Create a dictionary of the tensors
624
+ data_dict = {}
625
+ data_dict['image'] = images
626
+ data_dict['label'] = labels
627
+ data_dict['landmark'] = landmarks
628
+ data_dict['mask'] = masks
629
+ return data_dict
630
+
631
+ def __len__(self):
632
+ """
633
+ Return the length of the dataset.
634
+
635
+ Args:
636
+ None.
637
+
638
+ Returns:
639
+ An integer indicating the length of the dataset.
640
+
641
+ Raises:
642
+ AssertionError: If the number of images and labels in the dataset are not equal.
643
+ """
644
+ assert len(self.image_list) == len(self.label_list), 'Number of images and labels are not equal'
645
+ return len(self.image_list)
646
+
647
+
648
+ if __name__ == "__main__":
649
+ with open('/data/home/zhiyuanyan/DeepfakeBench/training/config/detector/video_baseline.yaml', 'r') as f:
650
+ config = yaml.safe_load(f)
651
+ train_set = DeepfakeAbstractBaseDataset(
652
+ config = config,
653
+ mode = 'train',
654
+ )
655
+ train_data_loader = \
656
+ torch.utils.data.DataLoader(
657
+ dataset=train_set,
658
+ batch_size=config['train_batchSize'],
659
+ shuffle=True,
660
+ num_workers=0,
661
+ collate_fn=train_set.collate_fn,
662
+ )
663
+ from tqdm import tqdm
664
+ for iteration, batch in enumerate(tqdm(train_data_loader)):
665
+ # print(iteration)
666
+ ...
667
+ # if iteration > 10:
668
+ # break
preprocessing/dataset_json/gpa.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3fb111163a61bdb552b4354897adddb63e73a15153cd5f51c4b76b3c226a5e9c
3
+ size 4382973
preprocessing/dataset_json/heygen.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3bb0f12c3d3fc0d045056b8b04d9f158275dde13c651343a667099f869c8bc96
3
+ size 1681524
preprocessing/dataset_json/others/Chameleon.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a2a154223e90dfc697d094f6a7f44888e22c39e1241be584994e099519970ea4
3
+ size 12495937
preprocessing/dataset_json/others/CoDiff.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d2255d70cec56cbfacec704cbbda4b240d4c110835b3454c82873fb04f2f8ad9
3
+ size 7851178
preprocessing/dataset_json/others/CollabDiff.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:564cf3e540fa21664e2711ae75013343281c880e5584bc2e8d5c6fc06d15990f
3
+ size 473682
preprocessing/dataset_json/others/DCFace.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6622e0a0dd8c552ab2b233c394848053a1b20fa461fea8e74ab99de5bcb87d32
3
+ size 8019871
preprocessing/dataset_json/others/DeeperForensics-1.0.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c3d582eae7754cb005a687d607e25861585247a6a81908364f32eab85d6af66
3
+ size 2606195
preprocessing/dataset_json/others/DiT_cdf.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb15e8b0b4bd900d6251b39f785145bc628a2e148bc7d5791db06fdc0c8b4492
3
+ size 5204091
preprocessing/dataset_json/others/DiT_ff.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1725104dfcc9b459b1e671a16bcc37ca1c1fd02cdad86aa2c1361edb47629c4
3
+ size 4677394
preprocessing/dataset_json/others/EFSAll_cdf.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae2487011b7dd66954830da3f84208ac280772159c950f50446ec6114db96e82
3
+ size 55801088
preprocessing/dataset_json/others/EFSAll_ff.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56daa5d2d011ad0bcef828979a11786ab0599f63063aea7c61dbd208f6e053ce
3
+ size 48399606
preprocessing/dataset_json/others/FRAll_cdf.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1db14cdd1e09a50eddeed1260fdc799e2370a5f8944b755d4dbe3cf640a79dfd
3
+ size 51106195
preprocessing/dataset_json/others/FRAll_ff.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9cbca5ced198c1f795a7a304c705d2fe4af5006adc41cf7f898f6f6c3de74624
3
+ size 67347051
preprocessing/dataset_json/others/FSAll_cdf.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:73939286d610f0d2da4cc589285690762ce070f77beb2b2cfa2b8068126f7efb
3
+ size 34632459
preprocessing/dataset_json/others/FSAll_ff.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ffaac2b1110f1616950364320eef1fd75e60e08273c73e1600413c4aba99fe05
3
+ size 53468909
preprocessing/dataset_json/others/FaceForensics++_vae.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a55d9e412945fbf17cd1f1f9c2fbabb43074541ba8707772c343821d108b39a
3
+ size 22330288
preprocessing/dataset_json/others/FreeDoM_I.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b0b820bb3074d176ce55feabc88effe1d60c1eb9d8c4207916fbe98eb239c0c7
3
+ size 7371858
preprocessing/dataset_json/others/FreeDoM_T.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:868d8666710d5a52172e20b66b2ff4831fb8371867d91f3ed066af6326cb97e6
3
+ size 7445199
preprocessing/dataset_json/others/MRAA_cdf.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4aa412d4c096609acf6474322137de6d1723e765002d7a52282e1a8f7f217a9e
3
+ size 4030920
preprocessing/dataset_json/others/MRAA_ff.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:057ba54e1573ea011a07f9fd1713adac01a96dc822e27ce1acba1d1d3730843b
3
+ size 5454366
preprocessing/dataset_json/others/SDXL.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:beb9ca562ef02ee5ef292bdcc46683c4a6fd42834ae6ad3680b0c4257ca87675
3
+ size 8257844
preprocessing/dataset_json/others/SDXL_Refine.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d739eb33786955d6a894c803fc6da0aefc275d78877f8c109718992c32eb9e21
3
+ size 8324707