MarshallCN commited on
Commit ·
f60b72c
1
Parent(s): b0ae3cd
upgrade gradio
Browse files- .gradio/certificate.pem +31 -0
- app.py +119 -25
- app_old.py +197 -0
- requirements.txt +3 -3
.gradio/certificate.pem
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-----BEGIN CERTIFICATE-----
|
| 2 |
+
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
|
| 31 |
+
-----END CERTIFICATE-----
|
app.py
CHANGED
|
@@ -28,34 +28,122 @@ yolom = YOLO(MODEL_PATH) # wrapper
|
|
| 28 |
# yolom_c = YOLO(MODEL_PATH_C) # wrapper
|
| 29 |
# put underlying module to eval on correct device might be needed in attacks functions
|
| 30 |
|
| 31 |
-
def run_detection_on_pil(img_pil: Image.Image, eval_model_state, conf: float = 0.45):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
"""
|
| 33 |
-
|
| 34 |
-
|
| 35 |
"""
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
| 37 |
img = np.array(img_pil)
|
| 38 |
-
|
| 39 |
-
eva_model = yolom if eval_model_state == "yolom" else YOLO(MODEL_PATH_C)
|
| 40 |
res = eva_model.predict(source=img, conf=conf, imgsz=imgsz, save=False, verbose=False)
|
| 41 |
r = res[0]
|
| 42 |
im_out = img.copy()
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
try:
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
cv2.rectangle(im_out, (x1, y1), (x2, y2), (0,255,0), 2)
|
| 54 |
-
cv2.putText(im_out, label, (x1, max(10,y1-5)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 1)
|
| 55 |
except Exception as e:
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
def detect_and_attack(image, eval_model_state, attack_mode, eps, alpha, iters, conf):
|
| 61 |
if image is None:
|
|
@@ -63,7 +151,7 @@ def detect_and_attack(image, eval_model_state, attack_mode, eps, alpha, iters, c
|
|
| 63 |
|
| 64 |
pil = Image.fromarray(image.astype('uint8'), 'RGB')
|
| 65 |
|
| 66 |
-
original_vis = run_detection_on_pil(pil, eval_model_state, conf=conf)
|
| 67 |
|
| 68 |
if attack_mode == "none":
|
| 69 |
return original_vis, None
|
|
@@ -79,7 +167,7 @@ def detect_and_attack(image, eval_model_state, attack_mode, eps, alpha, iters, c
|
|
| 79 |
print("Whitebox attack failed:", ex)
|
| 80 |
adv_pil = attacks.demo_random_perturbation(pil, eps=eps)
|
| 81 |
|
| 82 |
-
adv_vis = run_detection_on_pil(adv_pil, eval_model_state, conf=conf)
|
| 83 |
return original_vis, adv_vis
|
| 84 |
|
| 85 |
|
|
@@ -190,8 +278,14 @@ if __name__ == "__main__":
|
|
| 190 |
outputs=[out_orig, out_adv]
|
| 191 |
)
|
| 192 |
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
|
|
|
|
| 28 |
# yolom_c = YOLO(MODEL_PATH_C) # wrapper
|
| 29 |
# put underlying module to eval on correct device might be needed in attacks functions
|
| 30 |
|
| 31 |
+
# def run_detection_on_pil(img_pil: Image.Image, eval_model_state, conf: float = 0.45):
|
| 32 |
+
# """
|
| 33 |
+
# Use ultralytics wrapper predict to get a visualization image with boxes.
|
| 34 |
+
# This is inference-only and does not require gradient.
|
| 35 |
+
# """
|
| 36 |
+
# # ultralytics accepts numpy array (H,W,3) in RGB, we pass it directly
|
| 37 |
+
# img = np.array(img_pil)
|
| 38 |
+
# # use model.predict with verbose=False to avoid prints
|
| 39 |
+
# eva_model = yolom if eval_model_state == "yolom" else YOLO(MODEL_PATH_C)
|
| 40 |
+
# res = eva_model.predict(source=img, conf=conf, imgsz=imgsz, save=False, verbose=False)
|
| 41 |
+
# r = res[0]
|
| 42 |
+
# im_out = img.copy()
|
| 43 |
+
# # Boxes object may be empty
|
| 44 |
+
# try:
|
| 45 |
+
# boxes = r.boxes
|
| 46 |
+
# for box in boxes:
|
| 47 |
+
# xyxy = box.xyxy[0].cpu().numpy().astype(int)
|
| 48 |
+
# x1, y1, x2, y2 = map(int, xyxy)
|
| 49 |
+
# conf_score = float(box.conf[0].cpu().numpy())
|
| 50 |
+
# cls_id = int(box.cls[0].cpu().numpy())
|
| 51 |
+
# # label = f"{cls_id}:{conf_score:.2f}"
|
| 52 |
+
# label = f"{names[cls_id]}:{conf_score:.2f}"
|
| 53 |
+
# cv2.rectangle(im_out, (x1, y1), (x2, y2), (0,255,0), 2)
|
| 54 |
+
# cv2.putText(im_out, label, (x1, max(10,y1-5)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 1)
|
| 55 |
+
# except Exception as e:
|
| 56 |
+
# # if no boxes or structure unexpected, just return original
|
| 57 |
+
# pass
|
| 58 |
+
# return Image.fromarray(im_out)
|
| 59 |
+
def iou(a, b):
|
| 60 |
+
ax1, ay1, ax2, ay2 = a
|
| 61 |
+
bx1, by1, bx2, by2 = b
|
| 62 |
+
iw = max(0, min(ax2, bx2) - max(ax1, bx1))
|
| 63 |
+
ih = max(0, min(ay2, by2) - max(ay1, by1))
|
| 64 |
+
inter = iw * ih
|
| 65 |
+
if inter <= 0:
|
| 66 |
+
return 0.0
|
| 67 |
+
area_a = max(0, ax2 - ax1) * max(0, ay2 - ay1)
|
| 68 |
+
area_b = max(0, bx2 - bx1) * max(0, by2 - by1)
|
| 69 |
+
return inter / (area_a + area_b - inter + 1e-9)
|
| 70 |
+
|
| 71 |
+
# def center_and_diag(b): #IOU足够好 未启用
|
| 72 |
+
# x1, y1, x2, y2 = b
|
| 73 |
+
# cx = 0.5 * (x1 + x2); cy = 0.5 * (y1 + y2)
|
| 74 |
+
# diag = max(1e-9, ((x2 - x1)**2 + (y2 - y1)**2)**0.5)
|
| 75 |
+
# area = max(0, (x2 - x1)) * max(0, (y2 - y1))
|
| 76 |
+
# return cx, cy, diag, area
|
| 77 |
+
|
| 78 |
+
def run_detection_on_pil(img_pil: Image.Image, eval_model_state, conf: float = 0.45, GT_boxes=None):
|
| 79 |
"""
|
| 80 |
+
推理+可视化。GT_boxes 和返回的 preds 都是:
|
| 81 |
+
[{'xyxy': (x1,y1,x2,y2), 'cls': int, 'conf': float(optional)}]
|
| 82 |
"""
|
| 83 |
+
import numpy as np, cv2, math
|
| 84 |
+
from ultralytics import YOLO
|
| 85 |
+
|
| 86 |
+
# ---- 1) 推理 ----
|
| 87 |
img = np.array(img_pil)
|
| 88 |
+
eva_model = yolom if eval_model_state == "yolom" else YOLO(MODEL_PATH_C)
|
|
|
|
| 89 |
res = eva_model.predict(source=img, conf=conf, imgsz=imgsz, save=False, verbose=False)
|
| 90 |
r = res[0]
|
| 91 |
im_out = img.copy()
|
| 92 |
+
|
| 93 |
+
# 名称表(尽量稳)
|
| 94 |
+
names = getattr(r, "names", None)
|
| 95 |
+
if names is None and hasattr(eva_model, "model") and hasattr(eva_model.model, "names"):
|
| 96 |
+
names = eva_model.model.names
|
| 97 |
+
|
| 98 |
+
# ---- 2) 规整预测框到简单结构 ----
|
| 99 |
+
preds = []
|
| 100 |
try:
|
| 101 |
+
bxs = r.boxes
|
| 102 |
+
if bxs is not None and len(bxs) > 0:
|
| 103 |
+
for b in bxs:
|
| 104 |
+
xyxy = b.xyxy[0].detach().cpu().numpy().tolist()
|
| 105 |
+
x1, y1, x2, y2 = [int(v) for v in xyxy]
|
| 106 |
+
cls_id = int(b.cls[0].detach().cpu().numpy())
|
| 107 |
+
conf_score = float(b.conf[0].detach().cpu().numpy())
|
| 108 |
+
preds.append({'xyxy': (x1, y1, x2, y2), 'cls': cls_id, 'conf': conf_score})
|
|
|
|
|
|
|
| 109 |
except Exception as e:
|
| 110 |
+
print("collect preds error:", e)
|
| 111 |
+
|
| 112 |
+
# ---- 3) IoU 匹配 + 画框 ----
|
| 113 |
+
IOU_THR = 0.3
|
| 114 |
+
# CENTER_DIST_RATIO = 0.30 # 中心点距离 / 预测框对角线 <= 0.30 即视为同一目标
|
| 115 |
+
# AREA_RATIO_THR = 0.25 # 面积比例下限:min(area_p, area_g) / max(...) >= 0.25
|
| 116 |
+
gt_used = set()
|
| 117 |
+
|
| 118 |
+
for p in preds:
|
| 119 |
+
color = (0, 255, 0) # 同类:绿
|
| 120 |
+
px1, py1, px2, py2 = p['xyxy']
|
| 121 |
+
pname = names[p['cls']] if (names is not None and p['cls'] in getattr(names, 'keys', lambda: [])()) else (
|
| 122 |
+
names[p['cls']] if (isinstance(names, (list, tuple)) and 0 <= p['cls'] < len(names)) else str(p['cls'])
|
| 123 |
+
)
|
| 124 |
+
label = f"{pname}:{p.get('conf', 0.0):.2f}"
|
| 125 |
+
|
| 126 |
+
if GT_boxes != None:
|
| 127 |
+
# 找 IoU 最高的未用 GT
|
| 128 |
+
best_j, best_iou = -1, 0.0
|
| 129 |
+
for j, g in enumerate(GT_boxes):
|
| 130 |
+
if j in gt_used:
|
| 131 |
+
continue
|
| 132 |
+
i = iou(p['xyxy'], g['xyxy'])
|
| 133 |
+
if i > best_iou:
|
| 134 |
+
best_iou, best_j = i, j
|
| 135 |
+
|
| 136 |
+
# 颜色规则:匹配且同类=绿;匹配但异类=红;
|
| 137 |
+
if best_iou >= IOU_THR:
|
| 138 |
+
gt_used.add(best_j)
|
| 139 |
+
if p['cls'] != int(GT_boxes[best_j]['cls']):
|
| 140 |
+
color = (255, 0, 0) # 异类:红
|
| 141 |
+
|
| 142 |
+
cv2.rectangle(im_out, (px1, py1), (px2, py2), color, 2)
|
| 143 |
+
cv2.putText(im_out, label, (px1, max(10, py1 - 5)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1)
|
| 144 |
+
|
| 145 |
+
return Image.fromarray(im_out), preds
|
| 146 |
+
|
| 147 |
|
| 148 |
def detect_and_attack(image, eval_model_state, attack_mode, eps, alpha, iters, conf):
|
| 149 |
if image is None:
|
|
|
|
| 151 |
|
| 152 |
pil = Image.fromarray(image.astype('uint8'), 'RGB')
|
| 153 |
|
| 154 |
+
original_vis, GT_boxes = run_detection_on_pil(pil, eval_model_state, conf=conf, GT_boxes=None)
|
| 155 |
|
| 156 |
if attack_mode == "none":
|
| 157 |
return original_vis, None
|
|
|
|
| 167 |
print("Whitebox attack failed:", ex)
|
| 168 |
adv_pil = attacks.demo_random_perturbation(pil, eps=eps)
|
| 169 |
|
| 170 |
+
adv_vis, _ = run_detection_on_pil(adv_pil, eval_model_state, conf=conf, GT_boxes=GT_boxes)
|
| 171 |
return original_vis, adv_vis
|
| 172 |
|
| 173 |
|
|
|
|
| 278 |
outputs=[out_orig, out_adv]
|
| 279 |
)
|
| 280 |
|
| 281 |
+
demo.queue(default_concurrency_limit=2, max_size=20)
|
| 282 |
+
if os.getenv("SPACE_ID"):
|
| 283 |
+
demo.launch(
|
| 284 |
+
server_name="0.0.0.0",
|
| 285 |
+
server_port=int(os.getenv("PORT", 7860)),
|
| 286 |
+
show_error=True,
|
| 287 |
+
)
|
| 288 |
+
else:
|
| 289 |
+
demo.launch()
|
| 290 |
|
| 291 |
|
app_old.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import numpy as np
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import torch
|
| 6 |
+
from ultralytics import YOLO
|
| 7 |
+
import cv2
|
| 8 |
+
import attacks # 上面那个 attacks.py,确保和 app.py 在同一目录或可 import 的包路径
|
| 9 |
+
import os, glob
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# MODEL_PATH = "weights/yolov8s_3cls.pt"
|
| 13 |
+
MODEL_PATH = "weights/fed_model2.pt"
|
| 14 |
+
MODEL_PATH_C = "weights/yolov8s_3cls.pt"
|
| 15 |
+
|
| 16 |
+
names = ['car', 'van', 'truck']
|
| 17 |
+
imgsz = 640
|
| 18 |
+
|
| 19 |
+
SAMPLE_DIR = "./images/train"
|
| 20 |
+
SAMPLE_IMAGES = sorted([
|
| 21 |
+
p for p in glob.glob(os.path.join(SAMPLE_DIR, "*"))
|
| 22 |
+
if os.path.splitext(p)[1].lower() in [".jpg", ".jpeg", ".png", ".bmp", ".webp"]
|
| 23 |
+
])[:4] # 只取前4张
|
| 24 |
+
|
| 25 |
+
# Load ultralytics model (wrapper)
|
| 26 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 27 |
+
yolom = YOLO(MODEL_PATH) # wrapper
|
| 28 |
+
# yolom_c = YOLO(MODEL_PATH_C) # wrapper
|
| 29 |
+
# put underlying module to eval on correct device might be needed in attacks functions
|
| 30 |
+
|
| 31 |
+
def run_detection_on_pil(img_pil: Image.Image, eval_model_state, conf: float = 0.45):
|
| 32 |
+
"""
|
| 33 |
+
Use ultralytics wrapper predict to get a visualization image with boxes.
|
| 34 |
+
This is inference-only and does not require gradient.
|
| 35 |
+
"""
|
| 36 |
+
# ultralytics accepts numpy array (H,W,3) in RGB, we pass it directly
|
| 37 |
+
img = np.array(img_pil)
|
| 38 |
+
# use model.predict with verbose=False to avoid prints
|
| 39 |
+
eva_model = yolom if eval_model_state == "yolom" else YOLO(MODEL_PATH_C)
|
| 40 |
+
res = eva_model.predict(source=img, conf=conf, imgsz=imgsz, save=False, verbose=False)
|
| 41 |
+
r = res[0]
|
| 42 |
+
im_out = img.copy()
|
| 43 |
+
# Boxes object may be empty
|
| 44 |
+
try:
|
| 45 |
+
boxes = r.boxes
|
| 46 |
+
for box in boxes:
|
| 47 |
+
xyxy = box.xyxy[0].cpu().numpy().astype(int)
|
| 48 |
+
x1, y1, x2, y2 = map(int, xyxy)
|
| 49 |
+
conf_score = float(box.conf[0].cpu().numpy())
|
| 50 |
+
cls_id = int(box.cls[0].cpu().numpy())
|
| 51 |
+
# label = f"{cls_id}:{conf_score:.2f}"
|
| 52 |
+
label = f"{names[cls_id]}:{conf_score:.2f}"
|
| 53 |
+
cv2.rectangle(im_out, (x1, y1), (x2, y2), (0,255,0), 2)
|
| 54 |
+
cv2.putText(im_out, label, (x1, max(10,y1-5)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 1)
|
| 55 |
+
except Exception as e:
|
| 56 |
+
# if no boxes or structure unexpected, just return original
|
| 57 |
+
pass
|
| 58 |
+
return Image.fromarray(im_out)
|
| 59 |
+
|
| 60 |
+
def detect_and_attack(image, eval_model_state, attack_mode, eps, alpha, iters, conf):
|
| 61 |
+
if image is None:
|
| 62 |
+
return None, None
|
| 63 |
+
|
| 64 |
+
pil = Image.fromarray(image.astype('uint8'), 'RGB')
|
| 65 |
+
|
| 66 |
+
original_vis = run_detection_on_pil(pil, eval_model_state, conf=conf)
|
| 67 |
+
|
| 68 |
+
if attack_mode == "none":
|
| 69 |
+
return original_vis, None
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
if attack_mode == "fgsm":
|
| 73 |
+
adv_pil = attacks.fgsm_attack_on_detector(yolom, pil, eps=eps, device=device, imgsz=imgsz)
|
| 74 |
+
elif attack_mode == "pgd":
|
| 75 |
+
adv_pil = attacks.pgd_attack_on_detector(yolom, pil, eps=eps, alpha=alpha, iters=iters, device=device, imgsz=imgsz)
|
| 76 |
+
else:
|
| 77 |
+
adv_pil = attacks.demo_random_perturbation(pil, eps=eps)
|
| 78 |
+
except Exception as ex:
|
| 79 |
+
print("Whitebox attack failed:", ex)
|
| 80 |
+
adv_pil = attacks.demo_random_perturbation(pil, eps=eps)
|
| 81 |
+
|
| 82 |
+
adv_vis = run_detection_on_pil(adv_pil, eval_model_state, conf=conf)
|
| 83 |
+
return original_vis, adv_vis
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# Gradio UI
|
| 87 |
+
if __name__ == "__main__":
|
| 88 |
+
title = "Federated Adversarial Attack — FGSM/PGD Demo"
|
| 89 |
+
desc_html = (
|
| 90 |
+
"Adversarial examples are generated locally using a "
|
| 91 |
+
"<strong>client-side</strong> model’s gradients (white-box), then evaluated against the "
|
| 92 |
+
"<strong>server-side aggregated (FedAvg) central model</strong>. "
|
| 93 |
+
"If the perturbation transfers, it can "
|
| 94 |
+
"degrade or alter the FedAvg model’s predictions on the same input image."
|
| 95 |
+
)
|
| 96 |
+
with gr.Blocks(title=title) as demo:
|
| 97 |
+
# 标题居中
|
| 98 |
+
gr.Markdown(f"""
|
| 99 |
+
<div>
|
| 100 |
+
<h1 style='text-align:center;margin-bottom:0.2rem'>{title}</h1>
|
| 101 |
+
<p style='opacity:0.85'>{desc_html}</p>
|
| 102 |
+
</div>""")
|
| 103 |
+
|
| 104 |
+
with gr.Row():
|
| 105 |
+
# ===== 左列:两个输入区块 =====
|
| 106 |
+
with gr.Column(scale=5):
|
| 107 |
+
# 输入区块 1:上传窗口 & 样例选择 —— 左右并列
|
| 108 |
+
with gr.Row():
|
| 109 |
+
with gr.Column(scale=7):
|
| 110 |
+
in_img = gr.Image(type="numpy", label="Input image")
|
| 111 |
+
with gr.Column(scale=2):
|
| 112 |
+
if SAMPLE_IMAGES:
|
| 113 |
+
gr.Examples(
|
| 114 |
+
examples=SAMPLE_IMAGES,
|
| 115 |
+
inputs=[in_img],
|
| 116 |
+
label=f"Select from sample images",
|
| 117 |
+
examples_per_page=4,
|
| 118 |
+
# run_on_click 默认为 False(只填充,不执行)
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
# 输入 2:攻击与参数
|
| 122 |
+
with gr.Accordion("Attack mode", open=True):
|
| 123 |
+
attack_mode = gr.Radio(
|
| 124 |
+
choices=["none", "fgsm", "pgd", "random noise"],
|
| 125 |
+
value="fgsm",
|
| 126 |
+
label="",
|
| 127 |
+
show_label=False
|
| 128 |
+
)
|
| 129 |
+
eps = gr.Slider(0.0, 0.3, step=0.01, value=0.0314, label="eps")
|
| 130 |
+
alpha = gr.Slider(0.001, 0.05, step=0.001, value=0.0078, label="alpha (PGD step)")
|
| 131 |
+
iters = gr.Slider(1, 100, step=1, value=10, label="PGD iterations")
|
| 132 |
+
conf = gr.Slider(0.0, 1.0, step=0.01, value=0.45, label="Confidence threshold (live)")
|
| 133 |
+
|
| 134 |
+
with gr.Row():
|
| 135 |
+
btn_clear = gr.ClearButton(
|
| 136 |
+
components=[in_img, eps, alpha, iters, conf], # 不清空 attack_mode
|
| 137 |
+
value="Clear"
|
| 138 |
+
)
|
| 139 |
+
btn_submit = gr.Button("Submit", variant="primary")
|
| 140 |
+
|
| 141 |
+
# ===== 右列:两个输出区块 =====
|
| 142 |
+
with gr.Column(scale=5):
|
| 143 |
+
# 新增:评测模型选择
|
| 144 |
+
with gr.Row():
|
| 145 |
+
eval_choice = gr.Dropdown(
|
| 146 |
+
choices=[(f"Client model {MODEL_PATH}", "client"),
|
| 147 |
+
(f"Central model {MODEL_PATH_C}", "central")],
|
| 148 |
+
value="client", # ★ 初始值为合法 value
|
| 149 |
+
label="Evaluation model"
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
eval_model_state = gr.State(value="yolom")
|
| 153 |
+
|
| 154 |
+
# ★ 合并后的单一回调:规范化下拉值 + 返回(更新后的下拉值, 模型对象)
|
| 155 |
+
def on_eval_change(val: str):
|
| 156 |
+
if isinstance(val, (list, tuple)):
|
| 157 |
+
val = val[0] if len(val) else "client"
|
| 158 |
+
if val not in ("client", "central"):
|
| 159 |
+
val = "client"
|
| 160 |
+
model = "yolom" if val == "client" else "yolom_c"
|
| 161 |
+
return gr.update(value=val), model
|
| 162 |
+
|
| 163 |
+
# 页面加载时同步一次,避免初次为空/不一致
|
| 164 |
+
demo.load(
|
| 165 |
+
fn=on_eval_change,
|
| 166 |
+
inputs=eval_choice,
|
| 167 |
+
outputs=[eval_choice, eval_model_state]
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
# 仅这一条 change 绑定(删掉你原来那个只写 State 的 change,避免并发覆盖)
|
| 171 |
+
eval_choice.change(
|
| 172 |
+
fn=on_eval_change,
|
| 173 |
+
inputs=eval_choice,
|
| 174 |
+
outputs=[eval_choice, eval_model_state]
|
| 175 |
+
)
|
| 176 |
+
out_orig = gr.Image(label="Original detection")
|
| 177 |
+
out_adv = gr.Image(label="After attack detection")
|
| 178 |
+
|
| 179 |
+
# Submit:手动运行
|
| 180 |
+
btn_submit.click(
|
| 181 |
+
fn=detect_and_attack,
|
| 182 |
+
inputs=[in_img, eval_model_state, attack_mode, eps, alpha, iters, conf],
|
| 183 |
+
outputs=[out_orig, out_adv]
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
# 仅 conf 滑块“实时”
|
| 187 |
+
conf.release(
|
| 188 |
+
fn=detect_and_attack,
|
| 189 |
+
inputs=[in_img, eval_model_state, attack_mode, eps, alpha, iters, conf],
|
| 190 |
+
outputs=[out_orig, out_adv]
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
# demo.queue(concurrency_count=2, max_size=20)
|
| 194 |
+
demo.launch()
|
| 195 |
+
# demo.launch(server_name="0.0.0.0", server_port=7860)
|
| 196 |
+
|
| 197 |
+
|
requirements.txt
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
# --- Core ---
|
| 2 |
-
gradio==
|
| 3 |
-
gradio_client=
|
| 4 |
-
huggingface_hub=
|
| 5 |
ultralytics>=8.3.0
|
| 6 |
torch>=2.2.0
|
| 7 |
torchvision>=0.17.0
|
|
|
|
| 1 |
# --- Core ---
|
| 2 |
+
gradio==5.49.1
|
| 3 |
+
gradio_client>=1.13.0,<2
|
| 4 |
+
huggingface_hub>=0.29.0
|
| 5 |
ultralytics>=8.3.0
|
| 6 |
torch>=2.2.0
|
| 7 |
torchvision>=0.17.0
|