Spaces:
Sleeping
Sleeping
Commit
Β·
2898702
1
Parent(s):
38e5a7e
final CAM layers fixed
Browse files- 0.7 +0 -0
- app.py +97 -107
- requirements.txt +4 -1
0.7
ADDED
File without changes
|
app.py
CHANGED
@@ -1,156 +1,146 @@
|
|
1 |
-
# app.py
|
2 |
"""
|
3 |
-
Twoβstage
|
4 |
-
1. haywoodsloan/ai-image-detector-deploy β Real vsΒ AI (SwinβV2)
|
5 |
-
2. SuSy.pt β Likely generator (ResNetβbased)
|
6 |
|
7 |
-
|
8 |
-
|
9 |
-
|
|
|
10 |
"""
|
11 |
|
12 |
-
|
13 |
-
import numpy as np,
|
14 |
from PIL import Image
|
15 |
from torchvision import transforms
|
16 |
-
from skimage.feature import graycomatrix, graycoprops
|
17 |
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
18 |
from torchcam.methods import GradCAM
|
|
|
|
|
|
|
19 |
|
20 |
-
#
|
21 |
-
|
22 |
-
|
23 |
-
bin_model = AutoModelForImageClassification.from_pretrained(BIN_ID)
|
24 |
-
bin_model.eval()
|
25 |
|
26 |
-
|
|
|
|
|
|
|
|
|
27 |
|
28 |
-
#
|
29 |
-
|
30 |
-
CAM_LAYER_SUSY = "feature_extractor.resnet_model.layer4.1.relu"
|
31 |
|
32 |
-
GEN_CLASSES
|
33 |
-
|
34 |
-
"Stable Diffusion XL", "MJ V1/V2",
|
35 |
-
]
|
36 |
PATCH, TOP = 224, 5
|
37 |
|
38 |
-
#
|
39 |
-
def
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
mask = (mask - mask.min()) / (mask.max() - mask.min() + 1e-6)
|
51 |
-
|
52 |
-
|
|
|
53 |
|
54 |
-
#
|
55 |
-
to_tensor
|
56 |
-
|
57 |
|
58 |
-
def susy_predict(img: Image.Image)
|
59 |
w, h = img.size
|
60 |
npx, npy = max(1, w // PATCH), max(1, h // PATCH)
|
61 |
-
patches
|
62 |
|
63 |
for i in range(npx):
|
64 |
for j in range(npy):
|
65 |
x, y = i * PATCH, j * PATCH
|
66 |
-
patches[i
|
67 |
|
68 |
contrasts = []
|
69 |
for p in patches:
|
70 |
-
g =
|
71 |
glcm = graycomatrix(g, [5], [0], 256, symmetric=True, normed=True)
|
72 |
contrasts.append(graycoprops(glcm, "contrast")[0, 0])
|
73 |
|
74 |
-
idx
|
75 |
-
|
76 |
-
|
77 |
with torch.no_grad():
|
78 |
-
probs =
|
79 |
return dict(zip(GEN_CLASSES, probs))
|
80 |
|
81 |
-
#
|
82 |
def pipeline(img_arr):
|
83 |
img = Image.fromarray(img_arr) if isinstance(img_arr, np.ndarray) else img_arr
|
84 |
heatmaps = []
|
85 |
|
86 |
-
# Stageβ1
|
87 |
with torch.no_grad():
|
88 |
-
inp_bin = bin_proc(images=img, return_tensors="pt")
|
89 |
-
logits =
|
90 |
-
|
91 |
-
|
92 |
-
ai_conf
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
target_layer=CAM_LAYER_BIN,
|
100 |
-
class_idx=class_idx,
|
101 |
-
orig_pil=img
|
102 |
-
)
|
103 |
-
)
|
104 |
-
|
105 |
-
# defaults
|
106 |
-
msg, bar_df, bar_vis = f"Authentic ({real_conf*100:.1f} %)", None, False
|
107 |
-
|
108 |
-
# Stageβ2 if AI
|
109 |
if ai_conf > real_conf:
|
110 |
-
|
111 |
gen_probs = susy_predict(img)
|
112 |
-
bar_df
|
113 |
-
|
114 |
|
115 |
-
# SuSy heatβmap: choose mostβprobable generator class
|
116 |
with torch.no_grad():
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
grad_cam_overlay(
|
123 |
-
susy_model, t_inp,
|
124 |
-
target_layer=CAM_LAYER_SUSY,
|
125 |
-
class_idx=susy_class,
|
126 |
-
orig_pil=img
|
127 |
-
)
|
128 |
-
)
|
129 |
-
|
130 |
-
return msg, gr.update(value=bar_df, visible=bar_vis), heatmaps
|
131 |
-
|
132 |
-
# ββββββββββββ Gradio UI βββββββββββββββββββββββββββββββββββββββββββββ
|
133 |
-
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
134 |
-
gr.Markdown("## πΌοΈ Local AI Fake Detector")
|
135 |
|
|
|
|
|
|
|
136 |
with gr.Row():
|
137 |
img_in = gr.Image(type="numpy", label="Upload image")
|
138 |
btn = gr.Button("Detect")
|
139 |
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
title="Stepβ―2β―ββ―Likely generator",
|
145 |
-
y_label="probability",
|
146 |
-
visible=False
|
147 |
-
)
|
148 |
-
|
149 |
-
gal_cam = gr.Gallery(
|
150 |
-
label="Model attention heatβmaps",
|
151 |
-
columns=2, height=300, visible=True
|
152 |
-
)
|
153 |
|
154 |
-
btn.click(pipeline, inputs=img_in, outputs=[
|
155 |
|
156 |
demo.launch()
|
|
|
1 |
+
# app.py βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
2 |
"""
|
3 |
+
Twoβstage AIβimage detector with visual explainability
|
|
|
|
|
4 |
|
5 |
+
Stageβ1 : haywoodsloan/ai-image-detector-deploy (SwinβV2) β RealΒ vsΒ AI
|
6 |
+
β³ GradβCAM (torchcam) overlay
|
7 |
+
Stageβ2 : SuSy.pt (torchscript ResNet) β Generator
|
8 |
+
β³ Saliencyβgrad overlay (Captum), because hooks are disabled
|
9 |
"""
|
10 |
|
11 |
+
# βββββββββββββββββββββ Imports ββββββββββββββββββββββββββββββββββββββββ
|
12 |
+
import torch, numpy as np, pandas as pd, matplotlib.pyplot as plt
|
13 |
from PIL import Image
|
14 |
from torchvision import transforms
|
|
|
15 |
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
16 |
from torchcam.methods import GradCAM
|
17 |
+
from captum.attr import Saliency
|
18 |
+
from skimage.feature import graycomatrix, graycoprops
|
19 |
+
import gradio as gr
|
20 |
|
21 |
+
# βββββββββββββββββββ Runtime / models βββββββββββββββββββββββββββββββββ
|
22 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
23 |
+
plt.set_loglevel("ERROR")
|
|
|
|
|
24 |
|
25 |
+
# Stageβ1 (eager)
|
26 |
+
BIN_ID = "haywoodsloan/ai-image-detector-deploy"
|
27 |
+
bin_proc = AutoImageProcessor.from_pretrained(BIN_ID)
|
28 |
+
bin_mod = AutoModelForImageClassification.from_pretrained(BIN_ID).to(device).eval()
|
29 |
+
CAM_LAYER_BIN = "encoder.layers.3.blocks.1.layernorm_after"
|
30 |
|
31 |
+
# Stageβ2 (scripted)
|
32 |
+
susy_mod = torch.jit.load("SuSy.pt").to(device).eval() # ScriptModule
|
33 |
+
CAM_LAYER_SUSY = "feature_extractor.resnet_model.layer4.1.relu"
|
34 |
|
35 |
+
GEN_CLASSES = ["Stable Diffusion 1.x", "DALLΒ·E 3",
|
36 |
+
"MJ V5/V6", "Stable Diffusion XL", "MJ V1/V2"]
|
|
|
|
|
37 |
PATCH, TOP = 224, 5
|
38 |
|
39 |
+
# βββββββββββββββ Universal overlay helper βββββββββββββββββββββββββββββ
|
40 |
+
def overlay_explanation(model, model_inputs, target_layer, class_idx, base_img):
|
41 |
+
"""
|
42 |
+
β’ If model is eager (supports hooks) β GradβCAM via torchcam
|
43 |
+
β’ If model is ScriptModule β absoluteβgradient saliency via Captum
|
44 |
+
Returns an RGBA PIL image blended with the heatβmap.
|
45 |
+
"""
|
46 |
+
is_script = isinstance(model, torch.jit.ScriptModule)
|
47 |
+
|
48 |
+
# Prepare inputs for forward
|
49 |
+
forward_inputs = model_inputs if torch.is_tensor(model_inputs) else dict(model_inputs)
|
50 |
+
|
51 |
+
# ---------- Scripted: Captum Saliency ----------
|
52 |
+
if is_script:
|
53 |
+
model.zero_grad(set_to_none=True)
|
54 |
+
sal = Saliency(model)
|
55 |
+
if not torch.is_tensor(forward_inputs):
|
56 |
+
forward_inputs = forward_inputs["pixel_values"]
|
57 |
+
grads = sal.attribute(forward_inputs, target=class_idx).abs().mean(1, keepdim=True)
|
58 |
+
mask = grads.squeeze().detach().cpu().numpy()
|
59 |
+
# ---------- Eager: torchcam GradβCAM ----------
|
60 |
+
else:
|
61 |
+
mods = dict(model.named_modules())
|
62 |
+
tgt = mods.get(target_layer) or next(m for n, m in mods.items() if n.endswith(target_layer))
|
63 |
+
cam = GradCAM(model, target_layer=tgt)
|
64 |
+
outputs = (model(forward_inputs) if torch.is_tensor(forward_inputs)
|
65 |
+
else model(**forward_inputs))
|
66 |
+
logits = outputs.logits if hasattr(outputs, "logits") else outputs
|
67 |
+
mask = cam(class_idx, logits)[0].detach().cpu().numpy()
|
68 |
+
|
69 |
+
# normalise & overlay
|
70 |
mask = (mask - mask.min()) / (mask.max() - mask.min() + 1e-6)
|
71 |
+
heat = Image.fromarray((plt.cm.jet(mask)[:, :, :3] * 255).astype(np.uint8))\
|
72 |
+
.resize(base_img.size, Image.BICUBIC)
|
73 |
+
return Image.blend(base_img.convert("RGBA"), heat.convert("RGBA"), alpha=0.45)
|
74 |
|
75 |
+
# βββββββββββββ SuSy patchβranking helper ββββββββββββββββββββββββββββββ
|
76 |
+
to_tensor = transforms.ToTensor()
|
77 |
+
to_gray = transforms.Compose([transforms.PILToTensor(), transforms.Grayscale()])
|
78 |
|
79 |
+
def susy_predict(img: Image.Image):
|
80 |
w, h = img.size
|
81 |
npx, npy = max(1, w // PATCH), max(1, h // PATCH)
|
82 |
+
patches = np.zeros((npx * npy, PATCH, PATCH, 3), dtype=np.uint8)
|
83 |
|
84 |
for i in range(npx):
|
85 |
for j in range(npy):
|
86 |
x, y = i * PATCH, j * PATCH
|
87 |
+
patches[i*npy+j] = np.array(img.crop((x, y, x+PATCH, y+PATCH)).resize((PATCH, PATCH)))
|
88 |
|
89 |
contrasts = []
|
90 |
for p in patches:
|
91 |
+
g = to_gray(Image.fromarray(p)).squeeze(0).numpy()
|
92 |
glcm = graycomatrix(g, [5], [0], 256, symmetric=True, normed=True)
|
93 |
contrasts.append(graycoprops(glcm, "contrast")[0, 0])
|
94 |
|
95 |
+
idx = np.argsort(contrasts)[::-1][:TOP]
|
96 |
+
tens = torch.from_numpy(patches[idx].transpose(0,3,1,2)).float()/255.0
|
|
|
97 |
with torch.no_grad():
|
98 |
+
probs = susy_mod(tens.to(device)).softmax(-1).mean(0).cpu().numpy()[1:]
|
99 |
return dict(zip(GEN_CLASSES, probs))
|
100 |
|
101 |
+
# βββββββββββββββββββββ Pipeline βββββββββββββββββββββββββββββββββββββββ
|
102 |
def pipeline(img_arr):
|
103 |
img = Image.fromarray(img_arr) if isinstance(img_arr, np.ndarray) else img_arr
|
104 |
heatmaps = []
|
105 |
|
106 |
+
# Stageβ1
|
107 |
with torch.no_grad():
|
108 |
+
inp_bin = bin_proc(images=img, return_tensors="pt").to(device)
|
109 |
+
logits = bin_mod(**inp_bin).logits.softmax(-1)[0] # [AI, Real]
|
110 |
+
|
111 |
+
ai_conf, real_conf = logits
|
112 |
+
winner_idx = 0 if ai_conf >= real_conf else 1
|
113 |
+
heatmaps.append(overlay_explanation(bin_mod, inp_bin, CAM_LAYER_BIN, winner_idx, img))
|
114 |
+
|
115 |
+
verdict = f"Authentic ({real_conf*100:.1f} %)"
|
116 |
+
bar_df, show_bar = None, False
|
117 |
+
|
118 |
+
# Stageβ2 (only if AI)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
if ai_conf > real_conf:
|
120 |
+
verdict = f"AIβgenerated ({ai_conf*100:.1f} %)"
|
121 |
gen_probs = susy_predict(img)
|
122 |
+
bar_df = pd.DataFrame({"class": gen_probs.keys(), "prob": gen_probs.values()})
|
123 |
+
show_bar = True
|
124 |
|
|
|
125 |
with torch.no_grad():
|
126 |
+
susy_in = to_tensor(img.resize((224,224))).unsqueeze(0).to(device)
|
127 |
+
g_idx = susy_mod(susy_in)[0,1:].argmax().item() + 1
|
128 |
+
heatmaps.append(overlay_explanation(susy_mod, susy_in, CAM_LAYER_SUSY, g_idx, img))
|
129 |
+
|
130 |
+
return verdict, gr.update(value=bar_df, visible=show_bar), heatmaps
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
|
132 |
+
# βββββββββββββββββββββββββ UI βββββββββββββββββββββββββββββββββββββββββ
|
133 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
134 |
+
gr.Markdown("## πΌοΈ TwoβStage AI Fake DetectorΒ βΒ Explained with Heatβmaps")
|
135 |
with gr.Row():
|
136 |
img_in = gr.Image(type="numpy", label="Upload image")
|
137 |
btn = gr.Button("Detect")
|
138 |
|
139 |
+
txt_out = gr.Textbox(label="Verdict", interactive=False)
|
140 |
+
bar_out = gr.BarPlot(x="class", y="prob", title="Likely generator",
|
141 |
+
y_label="probability", visible=False)
|
142 |
+
gal_out = gr.Gallery(label="Heatβmaps", columns=2, height=320)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
143 |
|
144 |
+
btn.click(pipeline, inputs=img_in, outputs=[txt_out, bar_out, gal_out])
|
145 |
|
146 |
demo.launch()
|
requirements.txt
CHANGED
@@ -8,4 +8,7 @@ pydantic==2.10.6
|
|
8 |
wheel
|
9 |
huggingface_hub>=0.22
|
10 |
pandas
|
11 |
-
torchcam>=0.4
|
|
|
|
|
|
|
|
8 |
wheel
|
9 |
huggingface_hub>=0.22
|
10 |
pandas
|
11 |
+
torchcam>=0.4
|
12 |
+
matplotlib>=3.8
|
13 |
+
timm>=0.9.12
|
14 |
+
captum>=0.7
|