Naneet commited on
Commit
2aea336
·
verified ·
1 Parent(s): 6712bbe

Upload chest_x_ray.py

Browse files
Files changed (1) hide show
  1. chest_x_ray.py +44 -0
chest_x_ray.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torchvision.transforms as transforms
4
+ from PIL import Image
5
+ import gradio as gr
6
+ import warnings
7
+
8
+ warnings.filterwarnings("ignore")
9
+
10
+ # Define model
11
+ class ResNet_Classifier(nn.Module):
12
+ def __init__(self, num_classes=4):
13
+ super(ResNet_Classifier, self).__init__()
14
+ self.cnn = torch.hub.load('pytorch/vision:v0.10.0', 'resnet18', pretrained=False)
15
+ self.cnn.fc = nn.Linear(self.cnn.fc.in_features, num_classes)
16
+
17
+ def forward(self, x):
18
+ return self.cnn(x)
19
+
20
+ # Load model
21
+ model_path = "chest_x_ray.bin" # Adjust path as needed
22
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
23
+ model = ResNet_Classifier(num_classes=4).to(device)
24
+ model.load_state_dict(torch.load(model_path, map_location=device))
25
+ model.eval()
26
+
27
+ # Image preprocessing
28
+ transform = transforms.Compose([
29
+ transforms.Resize((256, 256)),
30
+ transforms.ToTensor()
31
+ ])
32
+
33
+ def predict(image):
34
+ image = transform(image).unsqueeze(0).to(device) # Add batch dimension
35
+ with torch.inference_mode():
36
+ output = model(image)
37
+
38
+ # Class mapping
39
+ labels = {0: "COVID19", 1: "NORMAL", 2: "PNEUMONIA", 3: "TUBERCULOSIS"}
40
+ return labels[int(output.argmax(dim=1)[0])]
41
+
42
+ # Launch Gradio app
43
+ app = gr.Interface(fn=predict, inputs="image", outputs="label")
44
+ app.launch()