File size: 12,543 Bytes
7a5fdce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
run_det_attacks.py

Usage example:
python run_det_attacks.py \
  --weights /mnt/data/.../best.pt \
  --source jjs_tmp/clean/images \
  --out jjs_tmp/adv \
  --methods FGSM,PGD \
  --eps 8/255 \
  --batch 4 \
  --img-size 640 \
  --device 0 \
  --main_exec /abs/path/to/main \
  --run_clean_main

Notes:
- This script uses function.attack.attack_api_det.DetectionEvasionAttacker.generate(...)
  to generate adversarial images. That function must support save_path and preserve format/size
  (we assume you've applied the modifications so save_path will save adv images with the same
  ext & size as the original).
- For each method, adv images are saved under: OUT/<METHOD>/images/
- After generation, the script symlinks or copies your provided main executable into OUT/<METHOD>/main
  and runs it in that directory (so it will create OUT/<METHOD>/result or results with txt files).
"""

import argparse
import os
import sys
import time
import shutil
import subprocess
from pathlib import Path
import json

# third-party
import torch
import numpy as np
from PIL import Image

# Import the detection attack API (make sure your PYTHONPATH includes project root)
try:
    from function.attack.attack_api_det import DetectionEvasionAttacker
except Exception as e:
    print("ERROR: cannot import DetectionEvasionAttacker from function.attack.attack_api_det:", e)
    raise

# -----------------------
# Utilities
# -----------------------
def safe_load_model(weights_path: str, map_location='cpu'):
    """
    Safe loading: try to use torch.load fallback to load saved checkpoint.
    If the checkpoint contains 'model' as nn.Module, return it.
    If checkpoint is a state_dict only, raise informative error (user must use attempt_load)
    """
    weights_path = str(weights_path)
    if not os.path.exists(weights_path):
        raise FileNotFoundError("Weights not found: " + weights_path)
    ck = torch.load(weights_path, map_location=map_location)
    # If the checkpoint is itself an nn.Module (rare), return it
    if isinstance(ck, torch.nn.Module):
        print("[safe_load_model] loaded nn.Module directly from checkpoint.")
        return ck
    # If it's dict and contains 'model' as nn.Module
    if isinstance(ck, dict):
        if 'model' in ck and isinstance(ck['model'], torch.nn.Module):
            print("[safe_load_model] checkpoint contains 'model' as nn.Module - using it.")
            return ck['model']
        if 'state_dict' in ck:
            # state_dict only; cannot reconstruct architecture here
            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'.")
    raise RuntimeError(f"Unknown checkpoint format: {type(ck)}. Consider using yolov7 attempt_load in your env.")

def make_symlink_or_copy(src: str, dst: str):
    src = str(src); dst = str(dst)
    try:
        if os.path.exists(dst):
            return
        os.symlink(src, dst)
    except Exception:
        # fallback to copy
        shutil.copy(src, dst)
        os.chmod(dst, 0o755)

def run_main_in_dir(main_exec: str, cwd: str, timeout: int = 300):
    """
    Run './main' in cwd (expects main_exec to be a file to copy or symlink into cwd as 'main').
    Return dict with rc, stdout, stderr.
    """
    # Ensure the exec exists in cwd
    tgt = Path(cwd) / "main"
    if not tgt.exists():
        raise FileNotFoundError(f"Expected main at {tgt} but not found. Ensure script installed main into method folder before calling run_main_in_dir.")
    try:
        proc = subprocess.run(["./main", "images/"], cwd=str(cwd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
        return {"rc": proc.returncode, "stdout": proc.stdout.decode('utf8', errors='ignore'), "stderr": proc.stderr.decode('utf8', errors='ignore')}
    except subprocess.TimeoutExpired as e:
        return {"rc": -1, "stdout": "", "stderr": f"Timeout after {timeout}s"}
    except Exception as e:
        return {"rc": -1, "stdout": "", "stderr": str(e)}

# -----------------------
# Main CLI
# -----------------------
def parse_args():
    p = argparse.ArgumentParser()
    p.add_argument('--weights', required=True, help='path to yolov7 weights (checkpoint).')
    p.add_argument('--source', required=True, help='directory with clean images (images/). Usually jjs_tmp/clean/images')
    p.add_argument('--out', required=True, help='output adv root. For each method we will create OUT/<METHOD>/images/')
    p.add_argument('--methods', help='comma-separated methods to run (FGSM,PGD,...). Must match attack_api_det methods.')
    p.add_argument('--eps', default='8/255', help='epsilon for attacks (specify like 8/255 or 0.0313725).')
    p.add_argument('--batch', type=int, default=4, help='batch size for generation')
    p.add_argument('--img-size', type=int, default=640, help='img size used in attacker (letterbox).')
    p.add_argument('--device', default='0', help='cuda device id or "cpu"')
    p.add_argument('--nc', type=int, default=5, help='number of classes (your dataset).')
    p.add_argument('--main_exec', default='./main', help='path to closed-source main executable used by the system.')
    p.add_argument('--run_clean_main', action='store_true', help='if set, run ./main in the clean folder to produce baseline results.')
    p.add_argument('--timeout_main', type=int, default=300, help='timeout seconds for each ./main run in method dir.')
    p.add_argument('--no_copy_main', action='store_true', help='if set do not copy/symlink main into method dir (assume it already exists).')

    # New Arguments for sample count and method-specific config
    p.add_argument('--n-samples', type=int, default=50, help='number of images to attack (required)')
    p.add_argument('--method-config', default=None,
                   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}}\'')
    
    return p.parse_args()

def parse_eps(eps_str):
    # support "8/255" or float strings
    try:
        if '/' in eps_str:
            a,b = eps_str.split('/')
            return float(a)/float(b)
        return float(eps_str)
    except:
        return float(eps_str)

def main():
    args = parse_args()
    device_str = args.device
    device = 'cpu' if device_str.lower() == 'cpu' else f'cuda:{int(device_str)}'
    outroot = Path(args.out)
    source_images = Path(args.source)
    main_exec_path = Path(args.main_exec).resolve()

    if not source_images.exists():
        raise SystemExit(f"Source images directory not found: {source_images}")

    methods = [m.strip() for m in args.methods.split(',') if m.strip()]
    eps = parse_eps(args.eps)

    print("[run_det_attacks] device:", device)
    print("[run_det_attacks] methods:", methods)
    print("[run_det_attacks] source_images:", source_images)
    print("[run_det_attacks] outroot:", outroot)
    print("[run_det_attacks] main_exec (abs):", main_exec_path)

    # 1) load model (safe)
    print("[run_det_attacks] Loading model checkpoint (torch.load fallback)...")
    try:
        model = safe_load_model(args.weights, map_location=device)
    except Exception as e:
        print("Failed to load model via safe_load_model():", e)
        raise

    # ensure model float and on device
    try:
        model = model.to(device)
        model = model.float()
    except Exception as e:
        print("Warning: failed to cast model to float/device:", e)

    # 2) instantiate attacker
    print("[run_det_attacks] Instantiating DetectionEvasionAttacker...")
    attacker = DetectionEvasionAttacker(model=model, device=device, nc=args.nc, img_size=args.img_size, verbose=True)

    # 3) image list
    img_paths = sorted([str(p) for p in source_images.glob('*') if p.suffix.lower() in ('.jpg','.jpeg','.png')])
    if not img_paths:
        raise SystemExit("No images found in source images folder: " + str(source_images))

    # 4) require n_samples
    if args.n_samples <= 0:
        raise SystemExit("--n-samples must be > 0")
    img_paths = img_paths[: args.n_samples]
    print(f"[run_det_attacks] attacking {len(img_paths)} images (n-samples={args.n_samples})")

    # 5) for each method, generate advs into outroot/<METHOD>/images and then run ./main there
    method_cfg = {}
    if args.method_config:
        try:
            if os.path.exists(args.method_config):
                with open(args.method_config, 'r', encoding='utf-8') as f:
                    method_cfg = json.load(f)
            else:
                method_cfg = json.loads(args.method_config)
        except Exception as e:
            raise SystemExit(f"Failed to parse --method-config: {e}")
    method_cfg = {k.upper(): v for k, v in method_cfg.items()}

    for method in methods:
        print(f"\n[run_det_attacks] Running method: {method}")
        method_images_dir = outroot / method / 'images'
        method_images_dir.mkdir(parents=True, exist_ok=True)

        # 确保 main 文件在 method 文件夹中
        method_root = outroot / method
        method_main_path = method_root / "main"
        clean_main_path = Path("main")
        if not method_main_path.exists():
            try:
                # 复制 main 文件
                shutil.copy(str(clean_main_path), str(method_main_path))
                method_main_path.chmod(0o755)  # 设置为可执行
                print(f"[run_det_attacks] Copied 'main' into method folder: {method_main_path}")
            except Exception as e:
                print(f"[run_det_attacks] Failed to copy main into {method_root}: {e}")

        # method-specific kwargs (from config)
        method_key = method.upper()
        method_kwargs = method_cfg.get(method_key, {}) if method_cfg else {}

        print(f"[run_det_attacks] Generating adversarials to: {method_images_dir}")
        try:
            adv_np, _, saved_paths = attacker.generate(
                method=method,
                img_paths=img_paths,
                source_folder=None,
                save_path=str(method_images_dir),
                batch=args.batch,
                img_size=args.img_size,
                **method_kwargs
            )
            print(f"[run_det_attacks] attacker.generate returned adv_np.shape {getattr(adv_np,'shape',None)} and saved {len(saved_paths)} files")
        except Exception as e:
            print(f"[run_det_attacks] ERROR: attacker.generate failed for method {method}: {e}")
            continue

        # ensure the method root has main executable (copy or symlink)
        method_root = outroot / method
        try:
            if not args.no_copy_main:
                tgt = method_root / "main"
                if not tgt.exists():
                    make_symlink_or_copy(str(main_exec_path), str(tgt))
                    tgt.chmod(0o755)
                    print(f"[run_det_attacks] Installed main into method folder: {tgt}")
        except Exception as e:
            print("[run_det_attacks] Warning: failed to install main into method folder:", e)

        # run ./main inside method_root
        print(f"[run_det_attacks] Running ./main in {method_root} to produce results (result/txt)...")
        try:
            rc_info = run_main_in_dir(str(main_exec_path), str(method_root), timeout=args.timeout_main)
            print(f"[run_det_attacks] main rc: {rc_info['rc']}")
            if rc_info['stderr']:
                print("[run_det_attacks] main stderr (truncated):", rc_info['stderr'][:800])
            if rc_info['stdout']:
                print("[run_det_attacks] main stdout (truncated):", rc_info['stdout'][:800])
        except Exception as e:
            print("[run_det_attacks] Error running main in method folder:", e)
            continue

        # quick sanity: check for result/txt or results/txt
        result_candidate_1 = method_root / 'result' / 'txt'
        result_candidate_2 = method_root / 'results' / 'txt'
        if result_candidate_1.exists():
            print("[run_det_attacks] Found result txts at:", result_candidate_1)
        elif result_candidate_2.exists():
            print("[run_det_attacks] Found result txts at:", result_candidate_2)
        else:
            print("[run_det_attacks] WARNING: no result txt folder found under method root after running main. Check main output and stderr above.")

    print("\n[run_det_attacks] All done.")

if __name__ == '__main__':
    main()