Upload anime-ai-detect-fucker/attack.py with huggingface_hub
Browse files- anime-ai-detect-fucker/attack.py +130 -0
anime-ai-detect-fucker/attack.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
from typing import Mapping
|
| 4 |
+
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from torch.nn import CrossEntropyLoss
|
| 8 |
+
from torchvision import transforms
|
| 9 |
+
from torchvision.utils import save_image
|
| 10 |
+
from transformers import BeitFeatureExtractor, BeitForImageClassification
|
| 11 |
+
|
| 12 |
+
from attacker import *
|
| 13 |
+
|
| 14 |
+
use_gpu = torch.cuda.is_available()
|
| 15 |
+
device = torch.device("cuda" if use_gpu else "cpu")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def make_args(args_=None):
|
| 19 |
+
parser = argparse.ArgumentParser(description='PyTorch MS_COCO Training')
|
| 20 |
+
|
| 21 |
+
parser.add_argument('inputs', type=str)
|
| 22 |
+
parser.add_argument('--out_dir', type=str, default='./output')
|
| 23 |
+
parser.add_argument('--target', type=str, default='auto', help='[auto, ai, human, same]')
|
| 24 |
+
parser.add_argument('--eps', type=float, default=8 / 8, help='Noise intensity ')
|
| 25 |
+
parser.add_argument('--step_size', type=float, default=1.087313 / 8, help='Attack step size')
|
| 26 |
+
parser.add_argument('--steps', type=int, default=20, help='Attack step count')
|
| 27 |
+
|
| 28 |
+
parser.add_argument('--test_atk', action='store_true')
|
| 29 |
+
|
| 30 |
+
return parser.parse_args(args_)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
IMAGE_EXTS = ('.bmp', '.dib', '.png', '.jpg', '.jpeg',
|
| 34 |
+
'.pbm', '.pgm', '.ppm', '.tif', '.tiff')
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class Attacker:
|
| 38 |
+
def __init__(self, args):
|
| 39 |
+
self.args = args
|
| 40 |
+
os.makedirs(args.out_dir, exist_ok=True)
|
| 41 |
+
|
| 42 |
+
print('正在加载模型...')
|
| 43 |
+
self.feature_extractor = BeitFeatureExtractor.from_pretrained('saltacc/anime-ai-detect')
|
| 44 |
+
self.model = BeitForImageClassification.from_pretrained('saltacc/anime-ai-detect')
|
| 45 |
+
if use_gpu:
|
| 46 |
+
self.model = self.model.cuda()
|
| 47 |
+
print('加载完毕')
|
| 48 |
+
|
| 49 |
+
if args.target == 'ai': # 攻击成被识别为AI
|
| 50 |
+
self.target = torch.tensor([1]).to(device)
|
| 51 |
+
elif args.target == 'human':
|
| 52 |
+
self.target = torch.tensor([0]).to(device)
|
| 53 |
+
else:
|
| 54 |
+
self.target = torch.tensor([0]).to(device)
|
| 55 |
+
|
| 56 |
+
dataset_mean_t = torch.tensor([0.5, 0.5, 0.5]).view(1, -1, 1, 1)
|
| 57 |
+
dataset_std_t = torch.tensor([0.5, 0.5, 0.5]).view(1, -1, 1, 1)
|
| 58 |
+
if use_gpu:
|
| 59 |
+
dataset_mean_t = dataset_mean_t.cuda()
|
| 60 |
+
dataset_std_t = dataset_std_t.cuda()
|
| 61 |
+
self.pgd = PGD(self.model, img_transform=(
|
| 62 |
+
lambda x: (x - dataset_mean_t) / dataset_std_t, lambda x: x * dataset_std_t + dataset_mean_t))
|
| 63 |
+
self.pgd.set_para(eps=(args.eps * 2) / 255, alpha=lambda: (args.step_size * 2) / 255, iters=args.steps)
|
| 64 |
+
if args.target != 'same':
|
| 65 |
+
self.pgd.set_loss(CrossEntropyLoss())
|
| 66 |
+
else:
|
| 67 |
+
def loss_same(a, b):
|
| 68 |
+
return -torch.exp((a[0, 0] - a[0, 1]) ** 2)
|
| 69 |
+
|
| 70 |
+
self.pgd.set_loss(loss_same)
|
| 71 |
+
|
| 72 |
+
def save_image(self, image, noise, img_name):
|
| 73 |
+
# 缩放图片只缩放噪声
|
| 74 |
+
W, H = image.size
|
| 75 |
+
noise = F.interpolate(noise, size=(H, W), mode='bicubic')
|
| 76 |
+
img_save = transforms.ToTensor()(image) + noise
|
| 77 |
+
save_image(img_save, os.path.join(self.args.out_dir, f'{img_name[:img_name.rfind(".")]}_atk.png'))
|
| 78 |
+
|
| 79 |
+
def attack_(self, image, step_func=None):
|
| 80 |
+
inputs = self.feature_extractor(images=image, return_tensors="pt")['pixel_values']
|
| 81 |
+
if use_gpu:
|
| 82 |
+
inputs = inputs.cuda()
|
| 83 |
+
|
| 84 |
+
if self.args.target == 'auto':
|
| 85 |
+
with torch.no_grad():
|
| 86 |
+
outputs = self.model(inputs)
|
| 87 |
+
logits = outputs.logits
|
| 88 |
+
cls = logits.argmax(-1).item()
|
| 89 |
+
target = torch.tensor([cls]).to(device)
|
| 90 |
+
else:
|
| 91 |
+
target = self.target
|
| 92 |
+
|
| 93 |
+
if self.args.test_atk:
|
| 94 |
+
self.test_image(inputs, 'before attack')
|
| 95 |
+
|
| 96 |
+
atk_img = self.pgd.attack(inputs, target, step_func)
|
| 97 |
+
|
| 98 |
+
noise = self.pgd.img_transform[1](atk_img).detach().cpu() - self.pgd.img_transform[1](inputs).detach().cpu()
|
| 99 |
+
|
| 100 |
+
if self.args.test_atk:
|
| 101 |
+
self.test_image(atk_img, 'after attack')
|
| 102 |
+
|
| 103 |
+
return atk_img, noise
|
| 104 |
+
|
| 105 |
+
def attack_one(self, path, step_func=None):
|
| 106 |
+
image = Image.open(path).convert('RGB')
|
| 107 |
+
atk_img, noise = self.attack_(image, step_func)
|
| 108 |
+
self.save_image(image, noise, os.path.basename(path))
|
| 109 |
+
|
| 110 |
+
def attack(self, path, step_func=None):
|
| 111 |
+
self.attack_one(path, step_func)
|
| 112 |
+
|
| 113 |
+
@torch.no_grad()
|
| 114 |
+
def test_image(self, img, pre_fix=None):
|
| 115 |
+
outputs = self.model(img)
|
| 116 |
+
logits = outputs.logits
|
| 117 |
+
_ = pre_fix
|
| 118 |
+
confidences = torch.softmax(logits.reshape(-1), dim=0)
|
| 119 |
+
return {self.model.config.id2label[i]: float(conf) for i, conf in enumerate(confidences)}
|
| 120 |
+
|
| 121 |
+
@torch.no_grad()
|
| 122 |
+
def image_predict(self, image: Image.Image) -> Mapping[str, float]:
|
| 123 |
+
inputs = self.feature_extractor(images=image, return_tensors="pt")['pixel_values']
|
| 124 |
+
return self.test_image(inputs)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
if __name__ == '__main__':
|
| 128 |
+
args = make_args()
|
| 129 |
+
attacker = Attacker(args)
|
| 130 |
+
attacker.attack(args.inputs)
|