Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,103 +1,130 @@
|
|
| 1 |
-
import
|
|
|
|
|
|
|
|
|
|
| 2 |
from PIL import Image
|
|
|
|
| 3 |
import requests
|
| 4 |
from io import BytesIO
|
| 5 |
import os
|
| 6 |
-
import
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
image = None
|
| 28 |
-
|
| 29 |
-
|
|
|
|
| 30 |
if uploaded_file:
|
| 31 |
-
image = Image.open(uploaded_file).convert(
|
| 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 |
-
with
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torchvision
|
| 3 |
+
import torchvision.transforms as transforms
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
from PIL import Image
|
| 6 |
+
import streamlit as st
|
| 7 |
import requests
|
| 8 |
from io import BytesIO
|
| 9 |
import os
|
| 10 |
+
import string
|
| 11 |
+
|
| 12 |
+
# Page config
|
| 13 |
+
st.set_page_config(page_title="Adversarial Self-Driving Test", layout="wide")
|
| 14 |
+
|
| 15 |
+
# Title & Description
|
| 16 |
+
st.title("Adversarial Self-Driving Car Tester")
|
| 17 |
+
st.markdown("Upload a traffic sign, or select from default images to **confuse the AI model** into causing a virtual accident!")
|
| 18 |
+
|
| 19 |
+
# Load model + labels
|
| 20 |
+
model = torchvision.models.resnet18(pretrained=True)
|
| 21 |
+
model.eval()
|
| 22 |
+
|
| 23 |
+
LABELS_URL = "https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt"
|
| 24 |
+
labels = requests.get(LABELS_URL).text.strip().split("\n")
|
| 25 |
+
|
| 26 |
+
# Base transform for model input
|
| 27 |
+
model_transform = transforms.Compose([
|
| 28 |
+
transforms.Resize((224, 224)),
|
| 29 |
+
transforms.ToTensor(),
|
| 30 |
+
])
|
| 31 |
+
|
| 32 |
+
# Layout Selection
|
| 33 |
+
layout = st.radio("Choose Input Method:", ["Upload Image", "Select Default Image"])
|
| 34 |
|
| 35 |
image = None
|
| 36 |
+
|
| 37 |
+
if layout == "Upload Image":
|
| 38 |
+
uploaded_file = st.file_uploader("π· Upload a traffic sign image", type=["jpg", "jpeg", "png", "bmp", "webp"])
|
| 39 |
if uploaded_file:
|
| 40 |
+
image = Image.open(uploaded_file).convert('RGB')
|
| 41 |
+
st.image(image, caption="Uploaded Image", use_container_width=True)
|
| 42 |
+
st.session_state.selected_default_image = None
|
| 43 |
+
elif layout == "Select Default Image":
|
| 44 |
+
supported_exts = (".jpg", ".jpeg", ".png", ".bmp", ".webp")
|
| 45 |
+
default_images = sorted([f for f in os.listdir("images") if f.lower().endswith(supported_exts)])
|
| 46 |
+
cols = st.columns(4)
|
| 47 |
+
|
| 48 |
+
for idx, img_file in enumerate(default_images):
|
| 49 |
+
with cols[idx % 4]:
|
| 50 |
+
img_path = os.path.join("images", img_file)
|
| 51 |
+
img = Image.open(img_path).resize((200, 200))
|
| 52 |
+
st.image(img, use_container_width=True)
|
| 53 |
+
button_label = f"Select {string.ascii_uppercase[idx]}"
|
| 54 |
+
if st.button(button_label, key=f"select_{img_file}"):
|
| 55 |
+
st.session_state.selected_default_image = img_path
|
| 56 |
+
|
| 57 |
+
if "selected_default_image" in st.session_state and st.session_state.selected_default_image:
|
| 58 |
+
selected_path = st.session_state.selected_default_image
|
| 59 |
+
image = Image.open(selected_path).convert('RGB')
|
| 60 |
+
st.markdown("#### Selected Default Image")
|
| 61 |
+
st.image(image, caption=os.path.basename(selected_path), use_container_width=True)
|
| 62 |
+
|
| 63 |
+
# Epsilon slider
|
| 64 |
+
epsilon = st.slider("Perturbation Strength (epsilon)", 0.001, 0.1, 0.01, step=0.001)
|
| 65 |
+
|
| 66 |
+
# Target class selector
|
| 67 |
+
target_class = st.selectbox(
|
| 68 |
+
"Confuse the model into predicting:",
|
| 69 |
+
options=[
|
| 70 |
+
(919, "Stop Sign"),
|
| 71 |
+
(717, "Speed Limit 60"),
|
| 72 |
+
(718, "Speed Limit 80"),
|
| 73 |
+
(400, "Speedboat (LOL why?)"),
|
| 74 |
+
],
|
| 75 |
+
format_func=lambda x: f"{x[0]} - {x[1]}"
|
| 76 |
+
)
|
| 77 |
+
target_class_id = target_class[0]
|
| 78 |
+
target_class_label = target_class[1]
|
| 79 |
+
|
| 80 |
+
# --- PREDICTION LOGIC ---
|
| 81 |
+
if image:
|
| 82 |
+
with st.spinner("π§ Running AI Model & Generating Adversarial Image..."):
|
| 83 |
+
# Save original size
|
| 84 |
+
original_size = image.size # (width, height)
|
| 85 |
+
|
| 86 |
+
# Prepare input
|
| 87 |
+
input_tensor = model_transform(image).unsqueeze(0)
|
| 88 |
+
input_tensor.requires_grad = True
|
| 89 |
+
|
| 90 |
+
# Original prediction
|
| 91 |
+
with torch.no_grad():
|
| 92 |
+
orig_out = model(input_tensor)
|
| 93 |
+
orig_pred_idx = orig_out.argmax().item()
|
| 94 |
+
orig_pred = labels[orig_pred_idx]
|
| 95 |
+
|
| 96 |
+
# FGSM Attack
|
| 97 |
+
output = model(input_tensor)
|
| 98 |
+
loss = F.cross_entropy(output, torch.tensor([target_class_id]))
|
| 99 |
+
loss.backward()
|
| 100 |
+
perturb = epsilon * input_tensor.grad.sign()
|
| 101 |
+
adv_tensor = torch.clamp(input_tensor + perturb, 0, 1)
|
| 102 |
+
|
| 103 |
+
# Resize perturbed tensor back to original image size for display
|
| 104 |
+
adv_image_tensor = adv_tensor.squeeze(0)
|
| 105 |
+
adv_image_pil = transforms.ToPILImage()(adv_image_tensor)
|
| 106 |
+
adv_image_resized = adv_image_pil.resize(original_size)
|
| 107 |
+
|
| 108 |
+
# Adversarial prediction
|
| 109 |
+
adv_input_resized = model_transform(adv_image_resized).unsqueeze(0)
|
| 110 |
+
with torch.no_grad():
|
| 111 |
+
adv_out = model(adv_input_resized)
|
| 112 |
+
adv_pred_idx = adv_out.argmax().item()
|
| 113 |
+
adv_pred = labels[adv_pred_idx]
|
| 114 |
+
|
| 115 |
+
# Display Results
|
| 116 |
+
col1, col2 = st.columns(2)
|
| 117 |
+
with col1:
|
| 118 |
+
st.image(image, caption="Original Image", use_container_width=True)
|
| 119 |
+
st.success(f"β
**Original Prediction:** `{orig_pred}`")
|
| 120 |
+
|
| 121 |
+
with col2:
|
| 122 |
+
st.image(adv_image_resized, caption="Adversarial Image", use_container_width=True)
|
| 123 |
+
if orig_pred != adv_pred:
|
| 124 |
+
st.warning(f"β οΈ **Adversarial Prediction:** `{adv_pred}`")
|
| 125 |
+
else:
|
| 126 |
+
st.success(f"β
**Adversarial Prediction:** `{adv_pred}`")
|
| 127 |
+
|
| 128 |
+
if orig_pred != adv_pred:
|
| 129 |
+
st.markdown("#### π¨ Accident Report")
|
| 130 |
+
st.error(f"The car thought a `{orig_pred}` was a `{adv_pred}`. That's a full-on self-driving fail!")
|