mou11 commited on
Commit
356016c
·
verified ·
1 Parent(s): f1815f7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -0
app.py CHANGED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import torch.nn as nn
4
+ import numpy as np
5
+ from torchvision import transforms
6
+ from transformers import ViTForImageClassification
7
+ from pytorch_grad_cam import GradCAM
8
+ from pytorch_grad_cam.utils.image import show_cam_on_image
9
+ from PIL import Image
10
+
11
+ # Device
12
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
13
+
14
+ # Transforms
15
+ test_transforms = transforms.Compose([
16
+ transforms.Resize((224, 224)),
17
+ transforms.ToTensor(),
18
+ transforms.Normalize(mean=[0.485, 0.456, 0.406],
19
+ std=[0.229, 0.224, 0.225])
20
+ ])
21
+
22
+ mean = np.array([0.485, 0.456, 0.406])
23
+ std = np.array([0.229, 0.224, 0.225])
24
+
25
+ # Load model
26
+ model = ViTForImageClassification.from_pretrained(
27
+ 'google/vit-base-patch16-224',
28
+ num_labels=2,
29
+ ignore_mismatched_sizes=True
30
+ )
31
+ model.load_state_dict(torch.load('vit_pneumonia_best.pth', map_location=device))
32
+ model = model.to(device)
33
+ model.eval()
34
+
35
+ # ViT wrapper for Grad-CAM
36
+ class ViTWrapper(nn.Module):
37
+ def __init__(self, model):
38
+ super().__init__()
39
+ self.model = model
40
+ def forward(self, x):
41
+ return self.model(x).logits
42
+
43
+ def reshape_transform(tensor, height=14, width=14):
44
+ result = tensor[:, 1:, :].reshape(tensor.size(0), height, width, tensor.size(2))
45
+ result = result.transpose(2, 3).transpose(1, 2)
46
+ return result
47
+
48
+ wrapped_model = ViTWrapper(model)
49
+ target_layers = [model.vit.encoder.layer[-1].layernorm_before]
50
+ cam = GradCAM(model=wrapped_model, target_layers=target_layers,
51
+ reshape_transform=reshape_transform)
52
+
53
+ # Prediction function
54
+ def predict(pil_image):
55
+ img_tensor = test_transforms(pil_image).unsqueeze(0).to(device)
56
+
57
+ with torch.no_grad():
58
+ output = model(img_tensor).logits
59
+ probs = torch.softmax(output, dim=1)[0]
60
+
61
+ grayscale_cam = cam(input_tensor=img_tensor)[0]
62
+
63
+ img_numpy = test_transforms(pil_image).permute(1, 2, 0).numpy()
64
+ img_numpy = std * img_numpy + mean
65
+ img_numpy = np.clip(img_numpy, 0, 1).astype(np.float32)
66
+
67
+ heatmap = show_cam_on_image(img_numpy, grayscale_cam, use_rgb=True)
68
+
69
+ label = {
70
+ "NORMAL": float(probs[0]),
71
+ "PNEUMONIA": float(probs[1])
72
+ }
73
+
74
+ return label, Image.fromarray(heatmap)
75
+
76
+ # Gradio interface
77
+ demo = gr.Interface(
78
+ fn=predict,
79
+ inputs=gr.Image(type="pil", label="Upload Chest X-Ray"),
80
+ outputs=[
81
+ gr.Label(label="Prediction"),
82
+ gr.Image(type="pil", label="Grad-CAM Heatmap")
83
+ ],
84
+ title="🫁 Pneumonia Detector",
85
+ description="Upload a chest X-ray image to detect pneumonia with explainable AI (Grad-CAM)",
86
+ )
87
+
88
+ demo.launch()