Upload 5 files
Browse files- .gitattributes +1 -0
- attack_api_det.py +373 -0
- best.pt +3 -0
- clip_coordinates.py +150 -0
- main +3 -0
- run_det_attacks.py +279 -0
.gitattributes
CHANGED
|
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
main filter=lfs diff=lfs merge=lfs -text
|
attack_api_det.py
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# function/attack/attack_api_det.py
|
| 2 |
+
"""
|
| 3 |
+
Detection attack helpers - detection-specific attack interface for YOLOv7-like models.
|
| 4 |
+
|
| 5 |
+
(修改点:_save_adv_tensor 支持 ref_path,用于保持原图片的格式与尺寸;generate() 在保存时传入 ref_path)
|
| 6 |
+
"""
|
| 7 |
+
import os
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import List, Optional, Tuple
|
| 10 |
+
import numpy as np
|
| 11 |
+
from PIL import Image
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
|
| 15 |
+
# Optional imports from yolov7 utils (letterbox / nms). If missing, use simple fallback.
|
| 16 |
+
try:
|
| 17 |
+
from utils.datasets import letterbox
|
| 18 |
+
from utils.general import non_max_suppression
|
| 19 |
+
_HAS_YOLO_UTILS = True
|
| 20 |
+
except Exception:
|
| 21 |
+
_HAS_YOLO_UTILS = False
|
| 22 |
+
|
| 23 |
+
# -------------------------
|
| 24 |
+
# Helpers: image <-> tensor
|
| 25 |
+
# -------------------------
|
| 26 |
+
def _letterbox_to_tensor(path: str, img_size: int = 640, device='cpu') -> Tuple[torch.Tensor, Tuple[int,int], Tuple[int,int,int]]:
|
| 27 |
+
img0 = Image.open(path).convert('RGB')
|
| 28 |
+
w0, h0 = img0.size
|
| 29 |
+
|
| 30 |
+
if _HAS_YOLO_UTILS:
|
| 31 |
+
np_img = np.array(img0)
|
| 32 |
+
img_lb, ratio, (dw, dh) = letterbox(np_img, new_shape=img_size)
|
| 33 |
+
img_arr = img_lb
|
| 34 |
+
try:
|
| 35 |
+
r = float(ratio) if ratio is not None else min(img_size / h0, img_size / w0)
|
| 36 |
+
except:
|
| 37 |
+
r = min(img_size / h0, img_size / w0)
|
| 38 |
+
else:
|
| 39 |
+
r = min(img_size / h0, img_size / w0)
|
| 40 |
+
new_w, new_h = int(w0 * r), int(h0 * r)
|
| 41 |
+
img_resized = img0.resize((new_w, new_h), Image.BILINEAR)
|
| 42 |
+
canvas = Image.new('RGB', (img_size, img_size), (114, 114, 114))
|
| 43 |
+
dw = (img_size - new_w) // 2
|
| 44 |
+
dh = (img_size - new_h) // 2
|
| 45 |
+
canvas.paste(img_resized, (dw, dh))
|
| 46 |
+
img_arr = np.array(canvas)
|
| 47 |
+
|
| 48 |
+
img_bgr = img_arr[:, :, ::-1].transpose(2, 0, 1).copy()
|
| 49 |
+
tensor = torch.from_numpy(img_bgr).float().unsqueeze(0) / 255.0 # 1,C,H,W
|
| 50 |
+
return tensor.to(device), (w0, h0), (int(dw) if 'dw' in locals() else 0, int(dh) if 'dh' in locals() else 0, float(r))
|
| 51 |
+
|
| 52 |
+
def _tensor_to_pil_rgb(tensor_bchw: torch.Tensor) -> Image.Image:
|
| 53 |
+
arr = (tensor_bchw.detach().cpu().squeeze(0).permute(1, 2, 0).numpy() * 255.0).round().astype('uint8') # HWC BGR
|
| 54 |
+
arr = arr[:, :, ::-1] # to RGB
|
| 55 |
+
return Image.fromarray(arr)
|
| 56 |
+
|
| 57 |
+
# -------------------------
|
| 58 |
+
# DetectionEvasionAttacker
|
| 59 |
+
# -------------------------
|
| 60 |
+
class DetectionEvasionAttacker:
|
| 61 |
+
def __init__(self, model: torch.nn.Module, device: str = 'cuda:0', nc: int = 5, img_size: int = 640, verbose: bool = False):
|
| 62 |
+
self.device = torch.device(device if isinstance(device, str) else device)
|
| 63 |
+
self.model = model.to(self.device)
|
| 64 |
+
self.nc = int(nc)
|
| 65 |
+
self.img_size = int(img_size)
|
| 66 |
+
self.verbose = verbose
|
| 67 |
+
|
| 68 |
+
def _model_dtype(self):
|
| 69 |
+
try:
|
| 70 |
+
return next(self.model.parameters()).dtype
|
| 71 |
+
except StopIteration:
|
| 72 |
+
return torch.float32
|
| 73 |
+
|
| 74 |
+
def _align_tensor_dtype(self, x: torch.Tensor) -> torch.Tensor:
|
| 75 |
+
x = x.to(self.device)
|
| 76 |
+
target_dtype = self._model_dtype()
|
| 77 |
+
if x.dtype != target_dtype:
|
| 78 |
+
x = x.to(dtype=target_dtype)
|
| 79 |
+
return x
|
| 80 |
+
|
| 81 |
+
def _preds_forward(self, imgs: torch.Tensor) -> torch.Tensor:
|
| 82 |
+
imgs = self._align_tensor_dtype(imgs)
|
| 83 |
+
out = self.model(imgs)
|
| 84 |
+
if isinstance(out, (tuple, list)):
|
| 85 |
+
preds = out[0]
|
| 86 |
+
else:
|
| 87 |
+
preds = out
|
| 88 |
+
if torch.is_tensor(preds):
|
| 89 |
+
return preds
|
| 90 |
+
try:
|
| 91 |
+
return torch.stack(preds, dim=0).to(self.device)
|
| 92 |
+
except Exception as e:
|
| 93 |
+
raise RuntimeError(f"Cannot parse model(...) output as preds tensor: {e}")
|
| 94 |
+
|
| 95 |
+
def _try_loss_forward(self, imgs: torch.Tensor, targets) -> torch.Tensor:
|
| 96 |
+
imgs = self._align_tensor_dtype(imgs)
|
| 97 |
+
out = self.model(imgs, targets)
|
| 98 |
+
if isinstance(out, (tuple, list)) and len(out) >= 1 and torch.is_tensor(out[0]):
|
| 99 |
+
return out[0]
|
| 100 |
+
if isinstance(out, dict) and 'loss' in out:
|
| 101 |
+
return out['loss']
|
| 102 |
+
raise RuntimeError("Model does not return training loss via model(imgs, targets).")
|
| 103 |
+
|
| 104 |
+
def _proxy_loss_from_preds(self, preds: torch.Tensor) -> torch.Tensor:
|
| 105 |
+
if preds is None:
|
| 106 |
+
return torch.tensor(0.0, device=self.device)
|
| 107 |
+
if preds.ndim == 3 and preds.shape[-1] >= 6:
|
| 108 |
+
obj = preds[..., 4].unsqueeze(-1)
|
| 109 |
+
cls_scores = preds[..., 5:5 + self.nc]
|
| 110 |
+
cls_prob = torch.softmax(cls_scores, dim=-1)
|
| 111 |
+
per_box = obj * cls_prob
|
| 112 |
+
per_image = per_box.sum(dim=1)
|
| 113 |
+
loss = per_image.sum()
|
| 114 |
+
return loss
|
| 115 |
+
return preds.sum()
|
| 116 |
+
|
| 117 |
+
def generate_fgsm_from_loss(self, imgs: torch.Tensor, targets, eps: float = 8/255.0) -> torch.Tensor:
|
| 118 |
+
self.model.train()
|
| 119 |
+
imgs = imgs.to(self.device)
|
| 120 |
+
imgs = self._align_tensor_dtype(imgs)
|
| 121 |
+
orig = imgs.detach().clone()
|
| 122 |
+
adv = orig.clone().detach().requires_grad_(True)
|
| 123 |
+
loss = self._try_loss_forward(adv, targets)
|
| 124 |
+
loss.backward()
|
| 125 |
+
grad = adv.grad.detach()
|
| 126 |
+
adv = adv + eps * grad.sign()
|
| 127 |
+
adv = torch.max(torch.min(adv, orig + eps), orig - eps)
|
| 128 |
+
adv = torch.clamp(adv, 0.0, 1.0)
|
| 129 |
+
return adv.detach()
|
| 130 |
+
|
| 131 |
+
def generate_pgd_from_loss(self, imgs: torch.Tensor, targets, eps: float = 8/255.0, alpha: float = 2/255.0, iters: int = 10, random_start: bool = True) -> torch.Tensor:
|
| 132 |
+
self.model.train()
|
| 133 |
+
imgs = imgs.to(self.device)
|
| 134 |
+
imgs = self._align_tensor_dtype(imgs)
|
| 135 |
+
orig = imgs.detach().clone()
|
| 136 |
+
if random_start:
|
| 137 |
+
adv = orig + (torch.rand_like(orig) * 2 - 1) * eps
|
| 138 |
+
else:
|
| 139 |
+
adv = orig.clone()
|
| 140 |
+
adv = torch.clamp(adv, 0.0, 1.0).detach().requires_grad_(True)
|
| 141 |
+
for i in range(iters):
|
| 142 |
+
if adv.grad is not None:
|
| 143 |
+
adv.grad.zero_()
|
| 144 |
+
loss = self._try_loss_forward(adv, targets)
|
| 145 |
+
loss.backward()
|
| 146 |
+
grad = adv.grad.detach()
|
| 147 |
+
adv = adv + alpha * grad.sign()
|
| 148 |
+
adv = torch.max(torch.min(adv, orig + eps), orig - eps)
|
| 149 |
+
adv = torch.clamp(adv, 0.0, 1.0).detach().requires_grad_(True)
|
| 150 |
+
if self.verbose and i % 5 == 0:
|
| 151 |
+
try:
|
| 152 |
+
print(f"[PGD loss] iter {i} loss {loss.item():.4f}")
|
| 153 |
+
except:
|
| 154 |
+
pass
|
| 155 |
+
return adv.detach()
|
| 156 |
+
|
| 157 |
+
def generate_fgsm_proxy(self, imgs: torch.Tensor, eps: float = 8/255.0) -> torch.Tensor:
|
| 158 |
+
self.model.eval()
|
| 159 |
+
imgs = imgs.to(self.device)
|
| 160 |
+
imgs = self._align_tensor_dtype(imgs)
|
| 161 |
+
orig = imgs.detach().clone()
|
| 162 |
+
adv = orig.clone().detach().requires_grad_(True)
|
| 163 |
+
preds = self._preds_forward(adv)
|
| 164 |
+
loss = self._proxy_loss_from_preds(preds)
|
| 165 |
+
loss.backward()
|
| 166 |
+
grad = adv.grad.detach()
|
| 167 |
+
adv = adv - eps * grad.sign()
|
| 168 |
+
adv = torch.max(torch.min(adv, orig + eps), orig - eps)
|
| 169 |
+
adv = torch.clamp(adv, 0.0, 1.0)
|
| 170 |
+
return adv.detach()
|
| 171 |
+
|
| 172 |
+
def generate_pgd_proxy(self, imgs: torch.Tensor, eps: float = 8/255.0, alpha: float = 2/255.0, iters: int = 10, random_start: bool = True) -> torch.Tensor:
|
| 173 |
+
self.model.eval()
|
| 174 |
+
imgs = imgs.to(self.device)
|
| 175 |
+
imgs = self._align_tensor_dtype(imgs)
|
| 176 |
+
orig = imgs.detach().clone()
|
| 177 |
+
if random_start:
|
| 178 |
+
adv = orig + (torch.rand_like(orig) * 2 - 1) * eps
|
| 179 |
+
else:
|
| 180 |
+
adv = orig.clone()
|
| 181 |
+
adv = torch.clamp(adv, 0.0, 1.0).detach().requires_grad_(True)
|
| 182 |
+
for i in range(iters):
|
| 183 |
+
if adv.grad is not None:
|
| 184 |
+
adv.grad.zero_()
|
| 185 |
+
preds = self._preds_forward(adv)
|
| 186 |
+
loss = self._proxy_loss_from_preds(preds)
|
| 187 |
+
loss.backward()
|
| 188 |
+
grad = adv.grad.detach()
|
| 189 |
+
adv = adv - alpha * grad.sign()
|
| 190 |
+
adv = torch.max(torch.min(adv, orig + eps), orig - eps)
|
| 191 |
+
adv = torch.clamp(adv, 0.0, 1.0).detach().requires_grad_(True)
|
| 192 |
+
if self.verbose and i % 5 == 0:
|
| 193 |
+
try:
|
| 194 |
+
print(f"[PGD proxy] iter {i} loss {loss.item():.4f}")
|
| 195 |
+
except:
|
| 196 |
+
pass
|
| 197 |
+
return adv.detach()
|
| 198 |
+
|
| 199 |
+
# -------------------------
|
| 200 |
+
# Batch helpers & generate API
|
| 201 |
+
# -------------------------
|
| 202 |
+
def _save_adv_tensor(self, tensor: torch.Tensor, out_path: str, ref_path: Optional[str] = None):
|
| 203 |
+
"""
|
| 204 |
+
Save adv tensor (1,C,H,W) as an image.
|
| 205 |
+
If ref_path is provided, mimic ref image's size & format (e.g., JPEG 448x416).
|
| 206 |
+
"""
|
| 207 |
+
pil = _tensor_to_pil_rgb(tensor) # PIL RGB
|
| 208 |
+
# If a reference image provided, try to read its format/size/mode
|
| 209 |
+
target_size = None
|
| 210 |
+
target_format = None
|
| 211 |
+
try:
|
| 212 |
+
if ref_path is not None and os.path.exists(ref_path):
|
| 213 |
+
ref_im = Image.open(ref_path)
|
| 214 |
+
target_format = ref_im.format # e.g., 'JPEG' or 'PNG'
|
| 215 |
+
target_size = ref_im.size # (W,H)
|
| 216 |
+
except Exception:
|
| 217 |
+
target_format = None
|
| 218 |
+
target_size = None
|
| 219 |
+
|
| 220 |
+
if target_size is not None:
|
| 221 |
+
# resize to reference size (width, height)
|
| 222 |
+
pil = pil.resize(target_size, Image.BILINEAR)
|
| 223 |
+
|
| 224 |
+
# Ensure directory exists
|
| 225 |
+
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
| 226 |
+
# Decide save format by reference or by extension
|
| 227 |
+
ext = Path(out_path).suffix.lower()
|
| 228 |
+
fmt = None
|
| 229 |
+
if target_format:
|
| 230 |
+
fmt = target_format.upper()
|
| 231 |
+
else:
|
| 232 |
+
if ext in ('.jpg', '.jpeg'):
|
| 233 |
+
fmt = 'JPEG'
|
| 234 |
+
elif ext in ('.png',):
|
| 235 |
+
fmt = 'PNG'
|
| 236 |
+
else:
|
| 237 |
+
fmt = 'PNG'
|
| 238 |
+
|
| 239 |
+
# Save accordingly
|
| 240 |
+
if fmt == 'JPEG':
|
| 241 |
+
pil.save(out_path, format='JPEG', quality=95)
|
| 242 |
+
else:
|
| 243 |
+
pil.save(out_path, format=fmt)
|
| 244 |
+
|
| 245 |
+
def generate(self, method: str = "FGSM",
|
| 246 |
+
img_paths: Optional[List[str]] = None,
|
| 247 |
+
source_folder: Optional[str] = None,
|
| 248 |
+
save_path: Optional[str] = None,
|
| 249 |
+
batch: int = 4,
|
| 250 |
+
img_size: int = None,
|
| 251 |
+
use_loss: bool = False,
|
| 252 |
+
targets_list: Optional[List] = None,
|
| 253 |
+
**kwargs):
|
| 254 |
+
"""
|
| 255 |
+
General generate API supporting multiple methods and per-method kwargs.
|
| 256 |
+
|
| 257 |
+
Parameters of interest in kwargs:
|
| 258 |
+
- eps (float)
|
| 259 |
+
- alpha (float)
|
| 260 |
+
- iters/int (int)
|
| 261 |
+
- random_start (bool)
|
| 262 |
+
- norm ('inf','2','1')
|
| 263 |
+
- other method-specific params forwarded.
|
| 264 |
+
|
| 265 |
+
img_paths: if provided, use this list (preferred).
|
| 266 |
+
source_folder: fallback to read all images from folder.
|
| 267 |
+
"""
|
| 268 |
+
if img_paths is None:
|
| 269 |
+
if source_folder:
|
| 270 |
+
p = Path(source_folder)
|
| 271 |
+
img_paths = sorted([str(x) for x in p.glob('*') if x.suffix.lower() in ('.jpg','.jpeg','.png')])
|
| 272 |
+
else:
|
| 273 |
+
raise ValueError("Either img_paths or source_folder must be provided")
|
| 274 |
+
# clip / cast
|
| 275 |
+
if img_size is None:
|
| 276 |
+
img_size = self.img_size
|
| 277 |
+
else:
|
| 278 |
+
img_size = int(img_size)
|
| 279 |
+
|
| 280 |
+
method_key = method.upper()
|
| 281 |
+
# default args
|
| 282 |
+
eps = float(kwargs.get('eps', kwargs.get('epsilon', 8/255.0)))
|
| 283 |
+
alpha = float(kwargs.get('alpha', 2/255.0))
|
| 284 |
+
iters = int(kwargs.get('iters', kwargs.get('steps', 10)))
|
| 285 |
+
random_start = bool(kwargs.get('random_start', True))
|
| 286 |
+
norm = str(kwargs.get('norm', 'inf')).lower()
|
| 287 |
+
|
| 288 |
+
# Prepare image list
|
| 289 |
+
if len(img_paths) == 0:
|
| 290 |
+
raise ValueError("No images to attack")
|
| 291 |
+
piclist = []
|
| 292 |
+
advs = []
|
| 293 |
+
|
| 294 |
+
# helper to chunk
|
| 295 |
+
for i in range(0, len(img_paths), batch):
|
| 296 |
+
batch_paths = img_paths[i:i + batch]
|
| 297 |
+
batch_tensors = []
|
| 298 |
+
for pth in batch_paths:
|
| 299 |
+
t, _, _ = _letterbox_to_tensor(pth, img_size=img_size, device=self.device)
|
| 300 |
+
t = t.float()
|
| 301 |
+
batch_tensors.append(t.squeeze(0))
|
| 302 |
+
x = torch.stack(batch_tensors, dim=0) # B,C,H,W
|
| 303 |
+
|
| 304 |
+
# Choose implementation
|
| 305 |
+
try:
|
| 306 |
+
if method_key in ("FGSM", "FFGSM"):
|
| 307 |
+
if use_loss and targets_list:
|
| 308 |
+
adv = self.generate_fgsm_from_loss(x, targets_list[i:i+batch], eps=eps)
|
| 309 |
+
else:
|
| 310 |
+
adv = self.generate_fgsm_proxy(x, eps=eps)
|
| 311 |
+
elif method_key in ("PGD", "PGDL", "BIM", "IFGSM", "I-FGSM", "BASIC_ITERATIVE"):
|
| 312 |
+
# PGD-like attacks: use proxy or loss versions
|
| 313 |
+
if use_loss and targets_list:
|
| 314 |
+
adv = self.generate_pgd_from_loss(x, targets_list[i:i+batch], eps=eps, alpha=alpha, iters=iters, random_start=random_start)
|
| 315 |
+
else:
|
| 316 |
+
adv = self.generate_pgd_proxy(x, eps=eps, alpha=alpha, iters=iters, random_start=random_start)
|
| 317 |
+
elif method_key in ("CW", "C&W", "CARLINI", "CARLINI-WAGNER"):
|
| 318 |
+
try:
|
| 319 |
+
import torchattacks
|
| 320 |
+
atk = torchattacks.CW(self.model, c=kwargs.get('c', 1e-3), kappa=kwargs.get('kappa', 0), steps=kwargs.get('cw_steps', 1000))
|
| 321 |
+
adv = atk(x, torch.zeros(x.size(0), dtype=torch.long, device=self.device))
|
| 322 |
+
except Exception as e:
|
| 323 |
+
raise RuntimeError("C&W attack requires 'torchattacks' package or custom implementation. "
|
| 324 |
+
"Fallback: use PGD-from-loss for detection models. Error: " + str(e))
|
| 325 |
+
elif method_key in ("DEEPLF", "DEEPOF", "DEEPLFOOL", "DEEPFOOL"):
|
| 326 |
+
try:
|
| 327 |
+
import torchattacks
|
| 328 |
+
atk = torchattacks.DeepFool(self.model)
|
| 329 |
+
adv = atk(x, torch.zeros(x.size(0), dtype=torch.long, device=self.device))
|
| 330 |
+
except Exception as e:
|
| 331 |
+
raise RuntimeError("DeepFool requires 'torchattacks' or custom impl. Fallback use PGD-from-loss.")
|
| 332 |
+
elif method_key in ("AUTOATTACK", "AUTO"):
|
| 333 |
+
try:
|
| 334 |
+
import torchattacks
|
| 335 |
+
atk = torchattacks.AutoAttack(self.model)
|
| 336 |
+
adv = atk(x, torch.zeros(x.size(0), dtype=torch.long, device=self.device))
|
| 337 |
+
except Exception as e:
|
| 338 |
+
raise RuntimeError("AutoAttack requires 'torchattacks' package. Fallback: use PGD.")
|
| 339 |
+
else:
|
| 340 |
+
# default fallback: PGD proxy
|
| 341 |
+
if use_loss and targets_list:
|
| 342 |
+
adv = self.generate_pgd_from_loss(x, targets_list[i:i+batch], eps=eps, alpha=alpha, iters=iters, random_start=random_start)
|
| 343 |
+
else:
|
| 344 |
+
adv = self.generate_pgd_proxy(x, eps=eps, alpha=alpha, iters=iters, random_start=random_start)
|
| 345 |
+
except Exception as e:
|
| 346 |
+
raise RuntimeError(f"Attack generation failed for method {method_key} on batch starting at {i}: {e}")
|
| 347 |
+
|
| 348 |
+
# save adv images if requested (preserve ref)
|
| 349 |
+
for bi, pth in enumerate(batch_paths):
|
| 350 |
+
tensor_single = adv[bi:bi + 1] # 1,C,H,W
|
| 351 |
+
if save_path:
|
| 352 |
+
orig_ext = Path(pth).suffix.lower()
|
| 353 |
+
fname = Path(pth).stem + f"_adv_{method_key}" + orig_ext
|
| 354 |
+
outp = os.path.join(save_path, fname)
|
| 355 |
+
# Save adversarial image
|
| 356 |
+
self._save_adv_tensor(tensor_single, outp, ref_path=pth)
|
| 357 |
+
piclist.append(outp)
|
| 358 |
+
|
| 359 |
+
# Calculate and save the perturbation to /jjs_tmp/perturbation/
|
| 360 |
+
orig_tensor, _, _ = _letterbox_to_tensor(pth, img_size=img_size, device=self.device)
|
| 361 |
+
perturbation = tensor_single - orig_tensor # Calculate perturbation
|
| 362 |
+
perturbation_dir = "jjs_tmp/perturbation/" # Specify the directory
|
| 363 |
+
os.makedirs(perturbation_dir, exist_ok=True) # Ensure directory exists
|
| 364 |
+
perturbation_path = os.path.join(perturbation_dir, f"{Path(pth).stem}_perturbation.bin")
|
| 365 |
+
perturbation.detach().cpu().numpy().tofile(perturbation_path)
|
| 366 |
+
#np.save(perturbation_path, perturbation.detach().cpu().numpy()) # Save perturbation as .npy
|
| 367 |
+
advs.append(tensor_single.detach().cpu().numpy())
|
| 368 |
+
|
| 369 |
+
adv_np = np.concatenate(advs, axis=0) if advs else np.zeros((0,3,img_size,img_size), dtype=np.float32)
|
| 370 |
+
return adv_np, None, piclist
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
|
best.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:418f908937b56867b01894035f0ce71f21edd1761ca87f7085982aa2f056620a
|
| 3 |
+
size 74839704
|
clip_coordinates.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Batch-clamp four-point detection coordinates; dry-run unless --apply is set.
|
| 2 |
+
|
| 3 |
+
Example:
|
| 4 |
+
python clip_coordinates.py --apply
|
| 5 |
+
Default bounds: x in [0,447], y in [0,415] for a 448x416 image.
|
| 6 |
+
Use --max-x 448 --max-y 416 only if your format uses continuous image-edge coordinates.
|
| 7 |
+
"""
|
| 8 |
+
import argparse
|
| 9 |
+
import hashlib
|
| 10 |
+
import json
|
| 11 |
+
import math
|
| 12 |
+
import os
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
import re
|
| 15 |
+
import shutil
|
| 16 |
+
import tempfile
|
| 17 |
+
from datetime import datetime
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def transform(data, path, max_x, max_y):
|
| 21 |
+
output = []
|
| 22 |
+
changed_rows = changed_values = upper = negative = rows = 0
|
| 23 |
+
for number, line in enumerate(data.splitlines(keepends=True), 1):
|
| 24 |
+
# Preserve a UTF-8 BOM, whitespace, line endings, class ID and confidence.
|
| 25 |
+
prefix = b'\xef\xbb\xbf' if number == 1 and line.startswith(b'\xef\xbb\xbf') else b''
|
| 26 |
+
body = line[len(prefix):]
|
| 27 |
+
tokens = list(re.finditer(rb'\S+', body))
|
| 28 |
+
if not tokens:
|
| 29 |
+
output.append(line)
|
| 30 |
+
continue
|
| 31 |
+
if len(tokens) != 10:
|
| 32 |
+
raise ValueError(f'{path}:{number}: expected 10 fields, got {len(tokens)}')
|
| 33 |
+
rows += 1
|
| 34 |
+
replacements = []
|
| 35 |
+
for i, token in enumerate(tokens[:8]):
|
| 36 |
+
value = float(token.group())
|
| 37 |
+
if not math.isfinite(value):
|
| 38 |
+
raise ValueError(f'{path}:{number}: non-finite coordinate')
|
| 39 |
+
limit = max_x if i % 2 == 0 else max_y
|
| 40 |
+
clipped = min(limit, max(0, value))
|
| 41 |
+
if clipped != value:
|
| 42 |
+
# Retain fixed-point precision of the original coordinate.
|
| 43 |
+
raw = token.group().decode('ascii')
|
| 44 |
+
precision = len(raw.split('.')[1]) if '.' in raw and 'e' not in raw.lower() else 6
|
| 45 |
+
replacements.append((token.start(), token.end(), f'{clipped:.{precision}f}'.encode('ascii')))
|
| 46 |
+
upper += value > limit
|
| 47 |
+
negative += value < 0
|
| 48 |
+
if replacements:
|
| 49 |
+
changed_rows += 1
|
| 50 |
+
changed_values += len(replacements)
|
| 51 |
+
for start, end, replacement in reversed(replacements):
|
| 52 |
+
body = body[:start] + replacement + body[end:]
|
| 53 |
+
output.append(prefix + body)
|
| 54 |
+
return b''.join(output), dict(rows=rows, changed_rows=changed_rows,
|
| 55 |
+
changed_values=changed_values,
|
| 56 |
+
upper_coordinates=upper, negative_coordinates=negative)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def atomic_write(path, data):
|
| 60 |
+
fd, name = tempfile.mkstemp(prefix='.clip-', suffix='.tmp', dir=path.parent)
|
| 61 |
+
try:
|
| 62 |
+
with os.fdopen(fd, 'wb') as stream:
|
| 63 |
+
stream.write(data)
|
| 64 |
+
stream.flush()
|
| 65 |
+
os.fsync(stream.fileno())
|
| 66 |
+
os.replace(name, path)
|
| 67 |
+
finally:
|
| 68 |
+
if os.path.exists(name):
|
| 69 |
+
os.unlink(name)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def main():
|
| 73 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 74 |
+
parser.add_argument('--root', type=Path, default=Path(r'D:\寅家验收\Perception'))
|
| 75 |
+
parser.add_argument('--max-x', type=float, default=447)
|
| 76 |
+
parser.add_argument('--max-y', type=float, default=415)
|
| 77 |
+
parser.add_argument('--apply', action='store_true')
|
| 78 |
+
parser.add_argument('--backup-dir', type=Path)
|
| 79 |
+
parser.add_argument('--report', type=Path)
|
| 80 |
+
args = parser.parse_args()
|
| 81 |
+
if not all(math.isfinite(v) and v > 0 for v in (args.max_x, args.max_y)):
|
| 82 |
+
parser.error('Bounds must be positive and finite')
|
| 83 |
+
root = args.root.resolve(strict=True)
|
| 84 |
+
directories = [root / name for name in ('JMC_Yichi_05S', 'Neta_S')]
|
| 85 |
+
if not all(p.is_dir() for p in directories):
|
| 86 |
+
parser.error('Both JMC_Yichi_05S and Neta_S directories are required')
|
| 87 |
+
plan = []
|
| 88 |
+
stats = {}
|
| 89 |
+
# Validate EVERY file before modifying any source file.
|
| 90 |
+
for directory in directories:
|
| 91 |
+
totals = dict(files=0, rows=0, changed_files=0, changed_rows=0,
|
| 92 |
+
changed_values=0, upper_coordinates=0, negative_coordinates=0)
|
| 93 |
+
paths = []
|
| 94 |
+
for parent, _, names in os.walk(directory):
|
| 95 |
+
paths.extend(Path(parent) / name for name in names if name.lower().endswith('.txt'))
|
| 96 |
+
for index, path in enumerate(sorted(paths), 1):
|
| 97 |
+
if index % 2000 == 0:
|
| 98 |
+
print(f'Checking {directory.name}: {index}/{len(paths)} TXT files', flush=True)
|
| 99 |
+
resolved = path.resolve(strict=True)
|
| 100 |
+
if not resolved.is_relative_to(directory.resolve()):
|
| 101 |
+
raise ValueError(f'File resolves outside intended directory: {path}')
|
| 102 |
+
original = path.read_bytes()
|
| 103 |
+
updated, counts = transform(original, path, args.max_x, args.max_y)
|
| 104 |
+
totals['files'] += 1
|
| 105 |
+
for key, value in counts.items():
|
| 106 |
+
totals[key] += value
|
| 107 |
+
if original != updated:
|
| 108 |
+
totals['changed_files'] += 1
|
| 109 |
+
plan.append((path, original, updated, counts))
|
| 110 |
+
stats[directory.name] = totals
|
| 111 |
+
print(f'Checked {directory.name}: {totals}', flush=True)
|
| 112 |
+
report = dict(mode='apply' if args.apply else 'dry-run', root=str(root),
|
| 113 |
+
bounds=dict(x=[0, args.max_x], y=[0, args.max_y]), statistics=stats)
|
| 114 |
+
if args.apply and plan:
|
| 115 |
+
backup = (args.backup_dir or Path(__file__).resolve().parent / 'coordinate_backups' /
|
| 116 |
+
datetime.now().strftime('%Y%m%d_%H%M%S_%f')).resolve()
|
| 117 |
+
if backup.is_relative_to(root):
|
| 118 |
+
raise ValueError('Backup directory must be outside the source root')
|
| 119 |
+
backup.mkdir(parents=True, exist_ok=False)
|
| 120 |
+
# Back up ALL affected files before the first overwrite.
|
| 121 |
+
for path, original, _, _ in plan:
|
| 122 |
+
if path.read_bytes() != original:
|
| 123 |
+
raise RuntimeError(f'Source changed during preflight: {path}')
|
| 124 |
+
dest = backup / path.relative_to(root)
|
| 125 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 126 |
+
shutil.copy2(path, dest)
|
| 127 |
+
if dest.read_bytes() != original:
|
| 128 |
+
raise RuntimeError(f'Backup verification failed: {path}')
|
| 129 |
+
print(f'Backed up {len(plan)} files to {backup}', flush=True)
|
| 130 |
+
report['backup_directory'] = str(backup)
|
| 131 |
+
report['modified_files'] = []
|
| 132 |
+
for path, original, updated, counts in plan:
|
| 133 |
+
if path.read_bytes() != original:
|
| 134 |
+
raise RuntimeError(f'Source changed before overwrite: {path}')
|
| 135 |
+
atomic_write(path, updated)
|
| 136 |
+
actual = path.read_bytes()
|
| 137 |
+
if actual != updated or transform(actual, path, args.max_x, args.max_y)[1]['changed_values']:
|
| 138 |
+
raise RuntimeError(f'Post-write verification failed: {path}')
|
| 139 |
+
report['modified_files'].append(dict(path=str(path), **counts,
|
| 140 |
+
original_sha256=hashlib.sha256(original).hexdigest(),
|
| 141 |
+
clipped_sha256=hashlib.sha256(updated).hexdigest()))
|
| 142 |
+
report['verification'] = 'All modified files match expected bytes and have in-range coordinates.'
|
| 143 |
+
if args.report:
|
| 144 |
+
args.report.parent.mkdir(parents=True, exist_ok=True)
|
| 145 |
+
args.report.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
|
| 146 |
+
print(json.dumps({k: v for k, v in report.items() if k != 'modified_files'}, ensure_ascii=False, indent=2))
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
if __name__ == '__main__':
|
| 150 |
+
main()
|
main
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4723f0488c788cd426cab5890175eb9b178cefd895b52d78895900369e8e368e
|
| 3 |
+
size 229517184
|
run_det_attacks.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
run_det_attacks.py
|
| 4 |
+
|
| 5 |
+
Usage example:
|
| 6 |
+
python run_det_attacks.py \
|
| 7 |
+
--weights /mnt/data/.../best.pt \
|
| 8 |
+
--source jjs_tmp/clean/images \
|
| 9 |
+
--out jjs_tmp/adv \
|
| 10 |
+
--methods FGSM,PGD \
|
| 11 |
+
--eps 8/255 \
|
| 12 |
+
--batch 4 \
|
| 13 |
+
--img-size 640 \
|
| 14 |
+
--device 0 \
|
| 15 |
+
--main_exec /abs/path/to/main \
|
| 16 |
+
--run_clean_main
|
| 17 |
+
|
| 18 |
+
Notes:
|
| 19 |
+
- This script uses function.attack.attack_api_det.DetectionEvasionAttacker.generate(...)
|
| 20 |
+
to generate adversarial images. That function must support save_path and preserve format/size
|
| 21 |
+
(we assume you've applied the modifications so save_path will save adv images with the same
|
| 22 |
+
ext & size as the original).
|
| 23 |
+
- For each method, adv images are saved under: OUT/<METHOD>/images/
|
| 24 |
+
- After generation, the script symlinks or copies your provided main executable into OUT/<METHOD>/main
|
| 25 |
+
and runs it in that directory (so it will create OUT/<METHOD>/result or results with txt files).
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
import argparse
|
| 29 |
+
import os
|
| 30 |
+
import sys
|
| 31 |
+
import time
|
| 32 |
+
import shutil
|
| 33 |
+
import subprocess
|
| 34 |
+
from pathlib import Path
|
| 35 |
+
import json
|
| 36 |
+
|
| 37 |
+
# third-party
|
| 38 |
+
import torch
|
| 39 |
+
import numpy as np
|
| 40 |
+
from PIL import Image
|
| 41 |
+
|
| 42 |
+
# Import the detection attack API (make sure your PYTHONPATH includes project root)
|
| 43 |
+
try:
|
| 44 |
+
from function.attack.attack_api_det import DetectionEvasionAttacker
|
| 45 |
+
except Exception as e:
|
| 46 |
+
print("ERROR: cannot import DetectionEvasionAttacker from function.attack.attack_api_det:", e)
|
| 47 |
+
raise
|
| 48 |
+
|
| 49 |
+
# -----------------------
|
| 50 |
+
# Utilities
|
| 51 |
+
# -----------------------
|
| 52 |
+
def safe_load_model(weights_path: str, map_location='cpu'):
|
| 53 |
+
"""
|
| 54 |
+
Safe loading: try to use torch.load fallback to load saved checkpoint.
|
| 55 |
+
If the checkpoint contains 'model' as nn.Module, return it.
|
| 56 |
+
If checkpoint is a state_dict only, raise informative error (user must use attempt_load)
|
| 57 |
+
"""
|
| 58 |
+
weights_path = str(weights_path)
|
| 59 |
+
if not os.path.exists(weights_path):
|
| 60 |
+
raise FileNotFoundError("Weights not found: " + weights_path)
|
| 61 |
+
ck = torch.load(weights_path, map_location=map_location)
|
| 62 |
+
# If the checkpoint is itself an nn.Module (rare), return it
|
| 63 |
+
if isinstance(ck, torch.nn.Module):
|
| 64 |
+
print("[safe_load_model] loaded nn.Module directly from checkpoint.")
|
| 65 |
+
return ck
|
| 66 |
+
# If it's dict and contains 'model' as nn.Module
|
| 67 |
+
if isinstance(ck, dict):
|
| 68 |
+
if 'model' in ck and isinstance(ck['model'], torch.nn.Module):
|
| 69 |
+
print("[safe_load_model] checkpoint contains 'model' as nn.Module - using it.")
|
| 70 |
+
return ck['model']
|
| 71 |
+
if 'state_dict' in ck:
|
| 72 |
+
# state_dict only; cannot reconstruct architecture here
|
| 73 |
+
raise RuntimeError("Checkpoint appears to be 'state_dict' only. Please ensure you can build the model architecture (yolov7 attempt_load) or provide checkpoint containing nn.Module under 'model'.")
|
| 74 |
+
raise RuntimeError(f"Unknown checkpoint format: {type(ck)}. Consider using yolov7 attempt_load in your env.")
|
| 75 |
+
|
| 76 |
+
def make_symlink_or_copy(src: str, dst: str):
|
| 77 |
+
src = str(src); dst = str(dst)
|
| 78 |
+
try:
|
| 79 |
+
if os.path.exists(dst):
|
| 80 |
+
return
|
| 81 |
+
os.symlink(src, dst)
|
| 82 |
+
except Exception:
|
| 83 |
+
# fallback to copy
|
| 84 |
+
shutil.copy(src, dst)
|
| 85 |
+
os.chmod(dst, 0o755)
|
| 86 |
+
|
| 87 |
+
def run_main_in_dir(main_exec: str, cwd: str, timeout: int = 300):
|
| 88 |
+
"""
|
| 89 |
+
Run './main' in cwd (expects main_exec to be a file to copy or symlink into cwd as 'main').
|
| 90 |
+
Return dict with rc, stdout, stderr.
|
| 91 |
+
"""
|
| 92 |
+
# Ensure the exec exists in cwd
|
| 93 |
+
tgt = Path(cwd) / "main"
|
| 94 |
+
if not tgt.exists():
|
| 95 |
+
raise FileNotFoundError(f"Expected main at {tgt} but not found. Ensure script installed main into method folder before calling run_main_in_dir.")
|
| 96 |
+
try:
|
| 97 |
+
proc = subprocess.run(["./main", "images/"], cwd=str(cwd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
|
| 98 |
+
return {"rc": proc.returncode, "stdout": proc.stdout.decode('utf8', errors='ignore'), "stderr": proc.stderr.decode('utf8', errors='ignore')}
|
| 99 |
+
except subprocess.TimeoutExpired as e:
|
| 100 |
+
return {"rc": -1, "stdout": "", "stderr": f"Timeout after {timeout}s"}
|
| 101 |
+
except Exception as e:
|
| 102 |
+
return {"rc": -1, "stdout": "", "stderr": str(e)}
|
| 103 |
+
|
| 104 |
+
# -----------------------
|
| 105 |
+
# Main CLI
|
| 106 |
+
# -----------------------
|
| 107 |
+
def parse_args():
|
| 108 |
+
p = argparse.ArgumentParser()
|
| 109 |
+
p.add_argument('--weights', required=True, help='path to yolov7 weights (checkpoint).')
|
| 110 |
+
p.add_argument('--source', required=True, help='directory with clean images (images/). Usually jjs_tmp/clean/images')
|
| 111 |
+
p.add_argument('--out', required=True, help='output adv root. For each method we will create OUT/<METHOD>/images/')
|
| 112 |
+
p.add_argument('--methods', help='comma-separated methods to run (FGSM,PGD,...). Must match attack_api_det methods.')
|
| 113 |
+
p.add_argument('--eps', default='8/255', help='epsilon for attacks (specify like 8/255 or 0.0313725).')
|
| 114 |
+
p.add_argument('--batch', type=int, default=4, help='batch size for generation')
|
| 115 |
+
p.add_argument('--img-size', type=int, default=640, help='img size used in attacker (letterbox).')
|
| 116 |
+
p.add_argument('--device', default='0', help='cuda device id or "cpu"')
|
| 117 |
+
p.add_argument('--nc', type=int, default=5, help='number of classes (your dataset).')
|
| 118 |
+
p.add_argument('--main_exec', default='./main', help='path to closed-source main executable used by the system.')
|
| 119 |
+
p.add_argument('--run_clean_main', action='store_true', help='if set, run ./main in the clean folder to produce baseline results.')
|
| 120 |
+
p.add_argument('--timeout_main', type=int, default=300, help='timeout seconds for each ./main run in method dir.')
|
| 121 |
+
p.add_argument('--no_copy_main', action='store_true', help='if set do not copy/symlink main into method dir (assume it already exists).')
|
| 122 |
+
|
| 123 |
+
# New Arguments for sample count and method-specific config
|
| 124 |
+
p.add_argument('--n-samples', type=int, default=50, help='number of images to attack (required)')
|
| 125 |
+
p.add_argument('--method-config', default=None,
|
| 126 |
+
help='JSON string or path to JSON file mapping method names to kwargs, e.g. \'{"FGSM":{"eps":0.03},"PGD":{"eps":0.03,"alpha":0.01,"iters":40}}\'')
|
| 127 |
+
|
| 128 |
+
return p.parse_args()
|
| 129 |
+
|
| 130 |
+
def parse_eps(eps_str):
|
| 131 |
+
# support "8/255" or float strings
|
| 132 |
+
try:
|
| 133 |
+
if '/' in eps_str:
|
| 134 |
+
a,b = eps_str.split('/')
|
| 135 |
+
return float(a)/float(b)
|
| 136 |
+
return float(eps_str)
|
| 137 |
+
except:
|
| 138 |
+
return float(eps_str)
|
| 139 |
+
|
| 140 |
+
def main():
|
| 141 |
+
args = parse_args()
|
| 142 |
+
device_str = args.device
|
| 143 |
+
device = 'cpu' if device_str.lower() == 'cpu' else f'cuda:{int(device_str)}'
|
| 144 |
+
outroot = Path(args.out)
|
| 145 |
+
source_images = Path(args.source)
|
| 146 |
+
main_exec_path = Path(args.main_exec).resolve()
|
| 147 |
+
|
| 148 |
+
if not source_images.exists():
|
| 149 |
+
raise SystemExit(f"Source images directory not found: {source_images}")
|
| 150 |
+
|
| 151 |
+
methods = [m.strip() for m in args.methods.split(',') if m.strip()]
|
| 152 |
+
eps = parse_eps(args.eps)
|
| 153 |
+
|
| 154 |
+
print("[run_det_attacks] device:", device)
|
| 155 |
+
print("[run_det_attacks] methods:", methods)
|
| 156 |
+
print("[run_det_attacks] source_images:", source_images)
|
| 157 |
+
print("[run_det_attacks] outroot:", outroot)
|
| 158 |
+
print("[run_det_attacks] main_exec (abs):", main_exec_path)
|
| 159 |
+
|
| 160 |
+
# 1) load model (safe)
|
| 161 |
+
print("[run_det_attacks] Loading model checkpoint (torch.load fallback)...")
|
| 162 |
+
try:
|
| 163 |
+
model = safe_load_model(args.weights, map_location=device)
|
| 164 |
+
except Exception as e:
|
| 165 |
+
print("Failed to load model via safe_load_model():", e)
|
| 166 |
+
raise
|
| 167 |
+
|
| 168 |
+
# ensure model float and on device
|
| 169 |
+
try:
|
| 170 |
+
model = model.to(device)
|
| 171 |
+
model = model.float()
|
| 172 |
+
except Exception as e:
|
| 173 |
+
print("Warning: failed to cast model to float/device:", e)
|
| 174 |
+
|
| 175 |
+
# 2) instantiate attacker
|
| 176 |
+
print("[run_det_attacks] Instantiating DetectionEvasionAttacker...")
|
| 177 |
+
attacker = DetectionEvasionAttacker(model=model, device=device, nc=args.nc, img_size=args.img_size, verbose=True)
|
| 178 |
+
|
| 179 |
+
# 3) image list
|
| 180 |
+
img_paths = sorted([str(p) for p in source_images.glob('*') if p.suffix.lower() in ('.jpg','.jpeg','.png')])
|
| 181 |
+
if not img_paths:
|
| 182 |
+
raise SystemExit("No images found in source images folder: " + str(source_images))
|
| 183 |
+
|
| 184 |
+
# 4) require n_samples
|
| 185 |
+
if args.n_samples <= 0:
|
| 186 |
+
raise SystemExit("--n-samples must be > 0")
|
| 187 |
+
img_paths = img_paths[: args.n_samples]
|
| 188 |
+
print(f"[run_det_attacks] attacking {len(img_paths)} images (n-samples={args.n_samples})")
|
| 189 |
+
|
| 190 |
+
# 5) for each method, generate advs into outroot/<METHOD>/images and then run ./main there
|
| 191 |
+
method_cfg = {}
|
| 192 |
+
if args.method_config:
|
| 193 |
+
try:
|
| 194 |
+
if os.path.exists(args.method_config):
|
| 195 |
+
with open(args.method_config, 'r', encoding='utf-8') as f:
|
| 196 |
+
method_cfg = json.load(f)
|
| 197 |
+
else:
|
| 198 |
+
method_cfg = json.loads(args.method_config)
|
| 199 |
+
except Exception as e:
|
| 200 |
+
raise SystemExit(f"Failed to parse --method-config: {e}")
|
| 201 |
+
method_cfg = {k.upper(): v for k, v in method_cfg.items()}
|
| 202 |
+
|
| 203 |
+
for method in methods:
|
| 204 |
+
print(f"\n[run_det_attacks] Running method: {method}")
|
| 205 |
+
method_images_dir = outroot / method / 'images'
|
| 206 |
+
method_images_dir.mkdir(parents=True, exist_ok=True)
|
| 207 |
+
|
| 208 |
+
# 确保 main 文件在 method 文件夹中
|
| 209 |
+
method_root = outroot / method
|
| 210 |
+
method_main_path = method_root / "main"
|
| 211 |
+
clean_main_path = Path("main")
|
| 212 |
+
if not method_main_path.exists():
|
| 213 |
+
try:
|
| 214 |
+
# 复制 main 文件
|
| 215 |
+
shutil.copy(str(clean_main_path), str(method_main_path))
|
| 216 |
+
method_main_path.chmod(0o755) # 设置为可执行
|
| 217 |
+
print(f"[run_det_attacks] Copied 'main' into method folder: {method_main_path}")
|
| 218 |
+
except Exception as e:
|
| 219 |
+
print(f"[run_det_attacks] Failed to copy main into {method_root}: {e}")
|
| 220 |
+
|
| 221 |
+
# method-specific kwargs (from config)
|
| 222 |
+
method_key = method.upper()
|
| 223 |
+
method_kwargs = method_cfg.get(method_key, {}) if method_cfg else {}
|
| 224 |
+
|
| 225 |
+
print(f"[run_det_attacks] Generating adversarials to: {method_images_dir}")
|
| 226 |
+
try:
|
| 227 |
+
adv_np, _, saved_paths = attacker.generate(
|
| 228 |
+
method=method,
|
| 229 |
+
img_paths=img_paths,
|
| 230 |
+
source_folder=None,
|
| 231 |
+
save_path=str(method_images_dir),
|
| 232 |
+
batch=args.batch,
|
| 233 |
+
img_size=args.img_size,
|
| 234 |
+
**method_kwargs
|
| 235 |
+
)
|
| 236 |
+
print(f"[run_det_attacks] attacker.generate returned adv_np.shape {getattr(adv_np,'shape',None)} and saved {len(saved_paths)} files")
|
| 237 |
+
except Exception as e:
|
| 238 |
+
print(f"[run_det_attacks] ERROR: attacker.generate failed for method {method}: {e}")
|
| 239 |
+
continue
|
| 240 |
+
|
| 241 |
+
# ensure the method root has main executable (copy or symlink)
|
| 242 |
+
method_root = outroot / method
|
| 243 |
+
try:
|
| 244 |
+
if not args.no_copy_main:
|
| 245 |
+
tgt = method_root / "main"
|
| 246 |
+
if not tgt.exists():
|
| 247 |
+
make_symlink_or_copy(str(main_exec_path), str(tgt))
|
| 248 |
+
tgt.chmod(0o755)
|
| 249 |
+
print(f"[run_det_attacks] Installed main into method folder: {tgt}")
|
| 250 |
+
except Exception as e:
|
| 251 |
+
print("[run_det_attacks] Warning: failed to install main into method folder:", e)
|
| 252 |
+
|
| 253 |
+
# run ./main inside method_root
|
| 254 |
+
print(f"[run_det_attacks] Running ./main in {method_root} to produce results (result/txt)...")
|
| 255 |
+
try:
|
| 256 |
+
rc_info = run_main_in_dir(str(main_exec_path), str(method_root), timeout=args.timeout_main)
|
| 257 |
+
print(f"[run_det_attacks] main rc: {rc_info['rc']}")
|
| 258 |
+
if rc_info['stderr']:
|
| 259 |
+
print("[run_det_attacks] main stderr (truncated):", rc_info['stderr'][:800])
|
| 260 |
+
if rc_info['stdout']:
|
| 261 |
+
print("[run_det_attacks] main stdout (truncated):", rc_info['stdout'][:800])
|
| 262 |
+
except Exception as e:
|
| 263 |
+
print("[run_det_attacks] Error running main in method folder:", e)
|
| 264 |
+
continue
|
| 265 |
+
|
| 266 |
+
# quick sanity: check for result/txt or results/txt
|
| 267 |
+
result_candidate_1 = method_root / 'result' / 'txt'
|
| 268 |
+
result_candidate_2 = method_root / 'results' / 'txt'
|
| 269 |
+
if result_candidate_1.exists():
|
| 270 |
+
print("[run_det_attacks] Found result txts at:", result_candidate_1)
|
| 271 |
+
elif result_candidate_2.exists():
|
| 272 |
+
print("[run_det_attacks] Found result txts at:", result_candidate_2)
|
| 273 |
+
else:
|
| 274 |
+
print("[run_det_attacks] WARNING: no result txt folder found under method root after running main. Check main output and stderr above.")
|
| 275 |
+
|
| 276 |
+
print("\n[run_det_attacks] All done.")
|
| 277 |
+
|
| 278 |
+
if __name__ == '__main__':
|
| 279 |
+
main()
|