telecomadm1145 commited on
Commit
11503dd
·
verified ·
1 Parent(s): 62bdf13

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +5 -29
app.py CHANGED
@@ -114,42 +114,18 @@ def infer(image_pil: Image.Image,
114
 
115
  transform = build_transform(is_training=False, interpolation=interpolation)
116
  input_tensor = transform(image_pil).unsqueeze(0).to(device)
117
-
118
- # (1) 分类预测
119
  logits = model(input_tensor)
120
  probs = F.softmax(logits, dim=1)[0]
121
  confidences = {class_names[i]: float(probs[i]) for i in range(NUM_CLASSES)}
122
 
123
- if not show_cam:
124
- return confidences, None
125
-
126
- # (2) Grad-CAM(多层级融合 → 均值)
127
- rgb_img = np.asarray(image_pil).astype(np.float32) / 255.0
128
- targets = [ClassifierOutputTarget(1)] # 固定看 AI 分类(索引 = 1)
129
-
130
- with GradCAM(model=model,
131
- target_layers=target_layers,
132
- reshape_transform=reshape_transform_swin) as cam:
133
-
134
- all_cams = cam(input_tensor, targets=targets,
135
- aug_smooth=True, eigen_smooth=True) # shape: [L, H', W']
136
-
137
- grayscale_cam = np.mean(all_cams, axis=0) # L 层取平均融合
138
- heatmap = Image.fromarray((grayscale_cam * 255).astype(np.uint8)) \
139
- .resize(image_pil.size, Image.Resampling.BILINEAR)
140
-
141
- cam_img = show_cam_on_image(rgb_img,
142
- np.asarray(heatmap).astype(np.float32) / 255.,
143
- use_rgb=True)
144
- cam_pil = Image.fromarray(cam_img)
145
-
146
- return confidences, cam_pil
147
 
148
  # ---------------------------------------------------------------------------
149
  # 7. Gradio UI
150
  def launch_app():
151
  with gr.Blocks() as demo:
152
- gr.Markdown("# 🖼️ AI vs. Non-AI Image Classifier (Swin-Large + Grad-CAM)")
153
 
154
  run_btn = gr.Button("🚀 Run")
155
 
@@ -163,8 +139,8 @@ def launch_app():
163
  in_img = gr.Image(type="pil", label="Upload an Image")
164
  out_lbl = gr.Label(num_top_classes=2, label="Predictions")
165
 
166
- def _run(img, inter, cam_flag):
167
- return infer(img, interpolation=inter, show_cam=False)
168
 
169
  run_btn.click(
170
  _run,
 
114
 
115
  transform = build_transform(is_training=False, interpolation=interpolation)
116
  input_tensor = transform(image_pil).unsqueeze(0).to(device)
117
+
 
118
  logits = model(input_tensor)
119
  probs = F.softmax(logits, dim=1)[0]
120
  confidences = {class_names[i]: float(probs[i]) for i in range(NUM_CLASSES)}
121
 
122
+ return confidences
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
  # ---------------------------------------------------------------------------
125
  # 7. Gradio UI
126
  def launch_app():
127
  with gr.Blocks() as demo:
128
+ gr.Markdown("# 🖼️ AI vs. Non-AI Image Classifier (with Swin-Large)")
129
 
130
  run_btn = gr.Button("🚀 Run")
131
 
 
139
  in_img = gr.Image(type="pil", label="Upload an Image")
140
  out_lbl = gr.Label(num_top_classes=2, label="Predictions")
141
 
142
+ def _run(img, inter):
143
+ return infer(img, interpolation=inter)
144
 
145
  run_btn.click(
146
  _run,