Spaces:
Sleeping
Sleeping
| import torch | |
| import torch.nn as nn | |
| import torchvision.transforms as transforms | |
| from PIL import Image | |
| import gradio as gr | |
| import torch.nn.functional as F | |
| # Define the model architecture | |
| class SimpleCNN(nn.Module): | |
| def __init__(self): | |
| super(SimpleCNN, self).__init__() | |
| self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1) | |
| self.pool = nn.MaxPool2d(2, 2) | |
| self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1) | |
| self.fc1 = nn.Linear(64 * 64 * 64, 512) | |
| self.fc2 = nn.Linear(512, 2) | |
| self.dropout = nn.Dropout(0.5) | |
| def forward(self, x): | |
| x = self.pool(F.relu(self.conv1(x))) | |
| x = self.pool(F.relu(self.conv2(x))) | |
| x = x.view(-1, 64 * 64 * 64) | |
| x = F.relu(self.fc1(x)) | |
| x = self.dropout(x) | |
| x = self.fc2(x) | |
| return x | |
| # Load the saved model | |
| model_path = 'modelv2.pth' | |
| model = SimpleCNN() | |
| model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu'))) | |
| model.eval() | |
| # Define transformations for images | |
| transform = transforms.Compose([ | |
| transforms.Resize((256, 256)), | |
| transforms.ToTensor() | |
| ]) | |
| # Define the prediction function | |
| def predict(image): | |
| image = Image.fromarray(image) | |
| image = transform(image).unsqueeze(0) | |
| with torch.no_grad(): | |
| outputs = model(image) | |
| probabilities = torch.softmax(outputs, dim=1) | |
| prob_benign = probabilities[0][0].item() | |
| prob_malignant = probabilities[0][1].item() | |
| return {'Benign': prob_benign, 'Malignant': prob_malignant} | |
| # Create Gradio interface | |
| iface = gr.Interface( | |
| fn=predict, | |
| inputs=gr.Image( label="Upload an Image"), | |
| outputs=gr.Label(num_top_classes=2, label="Predictions") | |
| ) | |
| # Run the interface | |
| if __name__ == "__main__": | |
| iface.launch() | |