File size: 25,166 Bytes
0788e19
 
 
 
 
 
 
 
54c5421
0788e19
 
 
 
54c5421
 
0788e19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6195c9e
0788e19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b343b32
 
 
 
0788e19
 
b343b32
 
 
 
 
 
 
 
 
 
0788e19
 
 
 
 
 
 
 
b343b32
 
 
 
0788e19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
import argparse
import importlib
import os
import sys
import urllib.request

import torch
import torch.nn as nn
from dotenv import load_dotenv
from huggingface_hub import snapshot_download
from torchvision import transforms
from transformers import CLIPModel

load_dotenv()

DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')


def download_weights():
    weights_path = './DeForge-AIGIBench-Models'
    token = os.getenv('HF_TOKEN')
    # Check if directory exists and has more than just the .git folder or similar
    if not os.path.exists(weights_path) or len(os.listdir(weights_path)) <= 1:
        print('Downloading weights from Hugging Face Hub...')
        snapshot_download(
            repo_id='TheKernel01/DeForge-AIGIBench-Models',
            local_dir=weights_path,
            repo_type='model',
            token=token,
        )
    return weights_path


# Download weights on import


class DetectorWrapper:
    def __init__(self):
        download_weights()
        self.model = None
        self.transform = None
        self.use_optimal_threshold = False

    @torch.inference_mode()
    def detect(self, data):
        # Default: sigmoid probability where high = fake if output dim is 1
        # If output dim is 2, use softmax[:, 1]
        out = self.model(data)
        if out.shape[1] == 1:
            return out.sigmoid().flatten()
        else:
            return out.softmax(dim=1)[:, 1].flatten()

    def _setup_path(self, path):
        """Append path to sys.path and clear related cached modules to avoid collisions."""
        # Convert relative path to absolute to ensure consistency
        if not os.path.isabs(path):
            if not os.path.exists(path):
                possible_path = os.path.join('..', path)
                if os.path.exists(possible_path):
                    path = possible_path

        abs_path = os.path.abspath(path)
        # Always move to the front to ensure precedence
        if abs_path in sys.path:
            sys.path.remove(abs_path)
        sys.path.insert(0, abs_path)

        # Clear modules that might conflict
        conflicting = (
            'networks',
            'models',
            'utils',
            'data',
            'model',
            'util',
            'dataset',
            'train',
        )
        to_delete = [
            m
            for m in list(sys.modules.keys())
            if m in conflicting or any(m.startswith(c + '.') for c in conflicting)
        ]
        for m in to_delete:
            del sys.modules[m]

        import importlib

        importlib.invalidate_caches()


class AIDE_Detector(DetectorWrapper):
    def __init__(self, model_path):
        super().__init__()
        self._setup_path('detector_codes/AIDE-main')
        from data.dct import DCT_base_Rec_Module
        from models.AIDE import AIDE

        self.model = AIDE(resnet_path=None, convnext_path=None)
        self.dct = DCT_base_Rec_Module()
        state_dict = torch.load(model_path, map_location='cpu', weights_only=False)
        msg = self.model.load_state_dict(
            state_dict['model'] if 'model' in state_dict else state_dict, strict=False
        )
        self.model.to(DEVICE).eval()
        self.dct.to(DEVICE)
        self.transform = transforms.Compose(
            [
                transforms.Resize((256, 256)),
                transforms.ToTensor(),
            ]
        )
        self.normalize = transforms.Normalize(
            mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
        )
        self.resize = transforms.Resize((256, 256))

    @torch.inference_mode()
    def detect(self, data):
        batch_stacked = []
        for i in range(data.shape[0]):
            img = data[i]
            x_minmin, x_maxmax, x_minmin1, x_maxmax1 = self.dct(img)
            stacked = torch.stack(
                [
                    self.normalize(self.resize(x_minmin)),
                    self.normalize(self.resize(x_maxmax)),
                    self.normalize(self.resize(x_minmin1)),
                    self.normalize(self.resize(x_maxmax1)),
                    self.normalize(img),
                ],
                dim=0,
            )
            batch_stacked.append(stacked)
        batch_data = torch.stack(batch_stacked, dim=0)
        out = self.model(batch_data)
        return out.softmax(dim=1)[:, 1].flatten()


class C2P_CLIP_Original(nn.Module):
    def __init__(
        self,
        name='openai/clip-vit-large-patch14',
        num_classes=1,
        hf_token=None,
    ):
        super(C2P_CLIP_Original, self).__init__()
        self.model = CLIPModel.from_pretrained(name, token=hf_token)
        del self.model.text_model
        del self.model.text_projection
        del self.model.logit_scale
        self.model.vision_model.requires_grad_(False)
        self.model.visual_projection.requires_grad_(False)
        self.model.fc = nn.Linear(768, num_classes)
        torch.nn.init.normal_(self.model.fc.weight.data, 0.0, 0.02)

    def encode_image(self, img):
        vision_outputs = self.model.vision_model(
            pixel_values=img,
            output_attentions=self.model.config.output_attentions,
            output_hidden_states=self.model.config.output_hidden_states,
            return_dict=self.model.config.return_dict,
        )
        pooled_output = vision_outputs[1]
        image_features = self.model.visual_projection(pooled_output)
        return image_features

    def forward(self, img):
        image_embeds = self.encode_image(img)
        image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
        return self.model.fc(image_embeds)


class C2P_CLIP_Original_Detector(DetectorWrapper):
    def __init__(self, model_path=None):
        super().__init__()
        if model_path is None:
            model_path = 'https://www.now61.com/f/95OefW/C2P_CLIP_release_20240901.zip'
        if model_path.startswith('http'):
            state_dict = torch.hub.load_state_dict_from_url(
                model_path, map_location='cpu', progress=True
            )
        else:
            state_dict = torch.load(model_path, map_location='cpu', weights_only=False)
        self.model = C2P_CLIP_Original(
            name='openai/clip-vit-large-patch14',
            num_classes=1,
            hf_token=os.getenv('HF_TOKEN'),
        )
        self.model.load_state_dict(state_dict, strict=True)
        self.model.to(DEVICE).eval()
        self.transform = transforms.Compose(
            [
                transforms.Resize((224, 224)),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=(0.48145466, 0.4578275, 0.40821073),
                    std=(0.26862954, 0.26130258, 0.27577711),
                ),
            ]
        )


class C2P_CLIP_Detector(DetectorWrapper):
    def __init__(self, model_path):
        super().__init__()
        self._setup_path('detector_codes/C2P-CLIP-DeepfakeDetection-main')
        from networks.c2p_clip import C2P_CLIP_Model

        self.model = C2P_CLIP_Model(
            name='openai/clip-vit-large-patch14',
            num_classes=1,
            hf_token=os.getenv('HF_TOKEN'),
        )
        state_dict = torch.load(model_path, map_location='cpu', weights_only=False)
        if 'model' in state_dict:
            state_dict = state_dict['model']
        new_state_dict = {}
        for k, v in state_dict.items():
            if k.startswith('module.'):
                new_state_dict[k[7:]] = v
            else:
                new_state_dict[k] = v
        self.model.load_state_dict(new_state_dict, strict=False)
        self.model.to(DEVICE).eval()
        self.transform = transforms.Compose(
            [
                transforms.Resize((224, 224)),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=(0.48145466, 0.4578275, 0.40821073),
                    std=(0.26862954, 0.26130258, 0.27577711),
                ),
            ]
        )

    def detect(self, img):
        return self.model.detect(img)


class C2P_DINOv2_Detector(DetectorWrapper):
    def __init__(self, model_path=None):
        super().__init__()
        self._setup_path('detector_codes/C2P-DINOv2-main')
        from model import C2P_DINOv2_Model

        self.model = C2P_DINOv2_Model(hf_token=os.getenv('HF_TOKEN'))
        if model_path is not None:
            state_dict = torch.load(model_path, map_location='cpu', weights_only=False)
            self.model.load_state_dict(
                state_dict['model_state_dict']
                if 'model_state_dict' in state_dict
                else state_dict,
                strict=False,
            )
        self.model.to(DEVICE).eval()
        self.transform = transforms.Compose(
            [
                transforms.Resize(256),
                transforms.CenterCrop(224),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
                ),
            ]
        )

    def detect(self, img):
        return self.model.detect(img)


class CLIPDetection_Detector(DetectorWrapper):
    def __init__(self, model_path):
        super().__init__()
        self._setup_path('detector_codes/CLIPDetection-main')
        from models.clip_models import CLIPModel

        self.model = CLIPModel(name='ViT-L/14', num_classes=1)
        self.model.load_state_dict(
            torch.load(model_path, map_location='cpu', weights_only=False)
        )
        self.model.to(DEVICE).eval()
        self.transform = transforms.Compose(
            [
                transforms.Resize((224, 224)),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=(0.48145466, 0.4578275, 0.40821073),
                    std=(0.26862954, 0.26130258, 0.27577711),
                ),
            ]
        )


class CNNDetection_Detector(DetectorWrapper):
    def __init__(self, model_path):
        super().__init__()
        self._setup_path('detector_codes/CNNDetection-master')
        from networks.resnet import resnet50

        self.model = resnet50(num_classes=1)
        state_dict = torch.load(model_path, map_location='cpu', weights_only=False)
        self.model.load_state_dict(
            state_dict['model'] if 'model' in state_dict else state_dict
        )
        self.model.to(DEVICE).eval()
        self.transform = transforms.Compose(
            [
                transforms.Resize((256, 256)),
                transforms.CenterCrop(224),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
                ),
            ]
        )


class DeForge_AI_Detector(DetectorWrapper):
    def __init__(self, model_path=None):
        super().__init__()
        self._setup_path('detector_codes/DeForge-AI-main')
        from model import DeForge_AI_Model

        checkpoint = None
        checkpoint_args = {}
        if model_path is not None:
            checkpoint = torch.load(model_path, map_location='cpu', weights_only=False)
            if isinstance(checkpoint, dict):
                checkpoint_args = checkpoint.get('args', {}) or {}
        model_kwargs = {
            'lora_r': checkpoint_args.get('lora_r', 16),
            'lora_alpha': checkpoint_args.get('lora_alpha', 32),
            'lora_dropout': checkpoint_args.get('lora_dropout', 0.5),
            'unfreeze_last_blocks': checkpoint_args.get('unfreeze_last_blocks', 0),
            'image_size': checkpoint_args.get('image_size', 256),
            'forensic_dim': checkpoint_args.get('forensic_dim', 256),
            'hf_token': os.getenv('HF_TOKEN'),
        }
        lora_target_modules = checkpoint_args.get('lora_target_modules')
        if isinstance(lora_target_modules, str):
            model_kwargs['lora_target_modules'] = [
                m.strip() for m in lora_target_modules.split(',') if m.strip()
            ]
        elif lora_target_modules:
            model_kwargs['lora_target_modules'] = lora_target_modules
        self.model = DeForge_AI_Model(**model_kwargs)
        if checkpoint is not None:
            self.model.load_state_dict(
                checkpoint['model_state_dict']
                if 'model_state_dict' in checkpoint
                else checkpoint,
                strict=False,
            )
        self.model.to(DEVICE).eval()
        size = model_kwargs['image_size']
        resize_size = max(int(round(size * 1.15)), size)
        self.transform = transforms.Compose(
            [
                transforms.Resize(resize_size),
                transforms.CenterCrop(size),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
                ),
            ]
        )

    def detect(self, img):
        return self.model.detect(img)


class DFFreq_Detector(DetectorWrapper):
    def __init__(self, model_path):
        super().__init__()
        self._setup_path('detector_codes/DFFreq-main')
        import networks.resnet as resnet_module

        importlib.reload(resnet_module)
        self.model = resnet_module.resnet50(num_classes=1)
        state_dict = torch.load(model_path, map_location='cpu', weights_only=False)
        self.model.load_state_dict(state_dict)
        self.model.to(DEVICE).eval()
        self.transform = transforms.Compose(
            [
                transforms.Resize((256, 256)),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
                ),
            ]
        )


class Effort_Detector(DetectorWrapper):
    def __init__(self, model_path):
        super().__init__()
        self._setup_path('detector_codes/Effort-AIGI-Detection')
        from models.clip_models import ClipModel

        opt = argparse.Namespace(use_svd=True)
        self.model = ClipModel(
            name='openai/clip-vit-large-patch14',
            opt=opt,
            num_classes=1,
            hf_token=os.getenv('HF_TOKEN'),
        )
        self.model.load_state_dict(
            torch.load(model_path, map_location='cpu', weights_only=False)
        )
        self.model.to(DEVICE).eval()
        self.transform = transforms.Compose(
            [
                transforms.Resize((224, 224)),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=(0.48145466, 0.4578275, 0.40821073),
                    std=(0.26862954, 0.26130258, 0.27577711),
                ),
            ]
        )


class FreqNet_Detector(DetectorWrapper):
    def __init__(self, model_path):
        super().__init__()
        self._setup_path('detector_codes/FreqNet-DeepfakeDetection-main')
        from networks.freqnet import FreqNet

        self.model = FreqNet(num_classes=1)
        self.model.load_state_dict(
            torch.load(model_path, map_location='cpu', weights_only=False)
        )
        self.model.to(DEVICE).eval()
        self.transform = transforms.Compose(
            [
                transforms.Resize((256, 256)),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
                ),
            ]
        )


class GramNet_Detector(DetectorWrapper):
    def __init__(self, model_path):
        super().__init__()
        self._setup_path('detector_codes/Gram-Net-main')
        import networks.resnet as resnet_module

        importlib.reload(resnet_module)
        self.model = resnet_module.resnet18(num_classes=1)
        self.model.load_state_dict(
            torch.load(model_path, map_location='cpu', weights_only=False)
        )
        self.model.to(DEVICE).eval()
        self.transform = transforms.Compose(
            [
                transforms.Resize((256, 256)),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
                ),
            ]
        )


class LGrad_Detector(DetectorWrapper):
    def __init__(self, model_path):
        super().__init__()
        self._setup_path('detector_codes/LGrad-master/CNNDetection')
        import networks.resnet as resnet_module

        importlib.reload(resnet_module)
        self.model = resnet_module.resnet50(num_classes=1)
        self.model.load_state_dict(
            torch.load(model_path, map_location='cpu', weights_only=False)
        )
        self.model.to(DEVICE).eval()
        self._setup_path('detector_codes/LGrad-master/img2gad_pytorch')
        from models import build_model

        self.discriminator = build_model(
            gan_type='stylegan',
            module='discriminator',
            resolution=256,
            label_size=0,
            image_channels=3,
        )
        disc_path = 'DeForge-AIGIBench-Models/LGrad-master/karras2019stylegan-bedrooms-256x256_discriminator.pth'
        if not os.path.exists(disc_path):
            os.makedirs(os.path.dirname(disc_path), exist_ok=True)
            urllib.request.urlretrieve(
                'https://lid-1302259812.cos.ap-nanjing.myqcloud.com/tmp/karras2019stylegan-bedrooms-256x256_discriminator.pth',
                disc_path,
            )
        self.discriminator.load_state_dict(
            torch.load(disc_path, map_location='cpu', weights_only=False), strict=True
        )
        self.discriminator.to(DEVICE).eval()
        self.transform = transforms.Compose(
            [transforms.Resize((256, 256)), transforms.ToTensor()]
        )
        self.transform_disc = transforms.Normalize(
            mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]
        )
        self.transform_resnet = transforms.Normalize(
            mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
        )

    def detect(self, data):
        disc_input = self.transform_disc(data)
        disc_input.requires_grad = True
        with torch.enable_grad():
            pre = self.discriminator(disc_input)
            grad = torch.autograd.grad(
                pre.sum(),
                disc_input,
                create_graph=False,
                retain_graph=False,
                allow_unused=False,
            )[0]
        b, c, h, w = grad.shape
        grad_flat = grad.view(b, -1)
        grad_min = grad_flat.min(dim=1, keepdim=True)[0].view(b, 1, 1, 1)
        grad_norm = grad - grad_min
        grad_flat_norm = grad_norm.view(b, -1)
        grad_max = grad_flat_norm.max(dim=1, keepdim=True)[0].view(b, 1, 1, 1)
        grad_norm = torch.where(grad_max != 0, grad_norm / grad_max, grad_norm)
        resnet_input = self.transform_resnet(grad_norm)
        with torch.no_grad():
            out = self.model(resnet_input)
            if out.shape[1] == 1:
                return out.sigmoid().flatten()
            else:
                return out.softmax(dim=1)[:, 1].flatten()


class LaDeDa_Detector(DetectorWrapper):
    def __init__(self, model_path):
        super().__init__()
        self._setup_path(
            'detector_codes/RealTime-DeepfakeDetection-in-the-RealWorld-main'
        )
        from networks.LaDeDa import LaDeDa9

        self.model = LaDeDa9(num_classes=1)
        self.model.fc = torch.nn.Linear(2048, 1)
        from collections import OrderedDict
        from copy import deepcopy

        state_dict = torch.load(model_path, map_location='cpu', weights_only=False)
        pretrained_dict = OrderedDict()
        for ki in state_dict.keys():
            pretrained_dict[ki] = deepcopy(state_dict[ki])
        self.model.load_state_dict(pretrained_dict, strict=True)
        self.model.to(DEVICE).eval()
        self.transform = transforms.Compose(
            [
                transforms.Resize((256, 256)),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
                ),
            ]
        )


class NPR_Detector(DetectorWrapper):
    def __init__(self, model_path):
        super().__init__()
        self._setup_path('detector_codes/NPR-DeepfakeDetection-main')
        from networks.resnet import resnet50

        self.model = resnet50(num_classes=1)
        self.model.load_state_dict(
            torch.load(model_path, map_location='cpu', weights_only=False)
        )
        self.model.to(DEVICE).eval()
        self.transform = transforms.Compose(
            [
                transforms.Resize((256, 256)),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
                ),
            ]
        )


class RIGID_Detector(DetectorWrapper):
    def __init__(self, model_path=None):
        super().__init__()
        self.use_optimal_threshold = True
        self._setup_path('detector_codes/RIGID-main')
        from rigid_detector import RIGID_Detector as RIGID_Impl

        self.model = RIGID_Impl(lamb=0.05)
        self.model.model.to(DEVICE)
        self.transform = transforms.Compose(
            [
                transforms.Resize((224, 224)),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)
                ),
            ]
        )

    @torch.inference_mode()
    def detect(self, data):
        return self.model.detect(data)


class Resnet50_Detector(DetectorWrapper):
    def __init__(self, model_path):
        super().__init__()
        self._setup_path('detector_codes/Resnet50-main')
        from networks.resnet import resnet50

        self.model = resnet50(num_classes=1)
        self.model.load_state_dict(
            torch.load(model_path, map_location='cpu', weights_only=False)
        )
        self.model.to(DEVICE).eval()
        self.transform = transforms.Compose(
            [
                transforms.Resize((256, 256)),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
                ),
            ]
        )


class SAFE_Detector(DetectorWrapper):
    def __init__(self, model_path):
        super().__init__()
        self._setup_path('detector_codes/SAFE-main')
        from models.resnet import resnet50

        self.model = resnet50(num_classes=2)
        state_dict = torch.load(model_path, map_location='cpu', weights_only=False)
        self.model.load_state_dict(
            state_dict['model'] if 'model' in state_dict else state_dict, strict=True
        )
        self.model.to(DEVICE).eval()
        self.transform = transforms.Compose(
            [
                transforms.Resize((256, 256)),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
                ),
            ]
        )


weight_mapping = {
    'AIDE': './DeForge-AIGIBench-Models/AIDE-main/model_epoch_best.pth',
    'C2P-CLIP': './DeForge-AIGIBench-Models/C2P-CLIP-DeepfakeDetection-main/model_epoch_best.pth',
    'C2P-CLIP-Original': None,
    'C2P-DINOv2': './DeForge-AIGIBench-Models/C2P-DINOv2-main/model_epoch_best.pth',
    'CLIPDetection': './DeForge-AIGIBench-Models/CLIPDetection-main/model_epoch_best.pth',
    'CNNDetection': './DeForge-AIGIBench-Models/CNNDetection-master/model_epoch_best.pth',
    'DeForge-AI': './DeForge-AIGIBench-Models/DeForge-AI-main/model_epoch_best.pth',
    'DFFreq': './DeForge-AIGIBench-Models/DFFreq-main/model_epoch_best.pth',
    'Effort': './DeForge-AIGIBench-Models/Effort-AIGI-Detection/model_epoch_best.pth',
    'FreqNet': './DeForge-AIGIBench-Models/FreqNet-DeepfakeDetection-main/model_epoch_best.pth',
    'GramNet': './DeForge-AIGIBench-Models/Gram-Net-main/model_epoch_best.pth',
    'LaDeDa': './DeForge-AIGIBench-Models/RealTime-DeepfakeDetection-in-the-RealWorld-main/model_epoch_best.pth',
    'LGrad': './DeForge-AIGIBench-Models/LGrad-master/model_epoch_best.pth',
    'NPR': './DeForge-AIGIBench-Models/NPR-DeepfakeDetection-main/model_epoch_best.pth',
    'RIGID': None,
    'Resnet50': './DeForge-AIGIBench-Models/Resnet50-main/model_epoch_best.pth',
    'SAFE': './DeForge-AIGIBench-Models/SAFE-main/model_epoch_best.pth',
}

detector_classes = {
    'AIDE': AIDE_Detector,
    'C2P-CLIP': C2P_CLIP_Detector,
    'C2P-CLIP-Original': C2P_CLIP_Original_Detector,
    'C2P-DINOv2': C2P_DINOv2_Detector,
    'CLIPDetection': CLIPDetection_Detector,
    'CNNDetection': CNNDetection_Detector,
    'DeForge-AI': DeForge_AI_Detector,
    'DFFreq': DFFreq_Detector,
    'Effort': Effort_Detector,
    'FreqNet': FreqNet_Detector,
    'GramNet': GramNet_Detector,
    'LaDeDa': LaDeDa_Detector,
    'LGrad': LGrad_Detector,
    'NPR': NPR_Detector,
    'RIGID': RIGID_Detector,
    'Resnet50': Resnet50_Detector,
    'SAFE': SAFE_Detector,
}