Download inference.py from PavanKumarD/Brain-Tumor-classification: direct link, hf CLI and curl.
- Browser
- Download file 2.45 kB
-
https://huggingface.co/spaces/PavanKumarD/Brain-Tumor-classification/resolve/main/inference.py
- Command line
-
hf download hf://spaces/PavanKumarD/Brain-Tumor-classification/inference.py
-
curl -L -o inference.py https://huggingface.co/spaces/PavanKumarD/Brain-Tumor-classification/resolve/main/inference.py
2.45 kB
| import torch | |
| import torch.nn as nn | |
| from torchvision import transforms | |
| from PIL import Image | |
| import io | |
| # Define the model class (must match training architecture) | |
| class custom_brain_tumor_model(nn.Module): | |
| def __init__(self, num_classes=4): | |
| super(custom_brain_tumor_model, self).__init__() | |
| self.conv_layers = nn.Sequential( | |
| nn.Conv2d(1, 64, kernel_size=3, padding=1), | |
| nn.BatchNorm2d(64), | |
| nn.ReLU(), | |
| nn.MaxPool2d(2, 2), | |
| nn.Conv2d(64, 128, kernel_size=3, padding=1), | |
| nn.BatchNorm2d(128), | |
| nn.ReLU(), | |
| nn.MaxPool2d(2, 2), | |
| nn.Conv2d(128, 256, kernel_size=3, padding=1), | |
| nn.BatchNorm2d(256), | |
| nn.ReLU(), | |
| nn.MaxPool2d(2, 2), | |
| nn.Conv2d(256, 512, kernel_size=3, padding=1), | |
| nn.BatchNorm2d(512), | |
| nn.ReLU(), | |
| nn.MaxPool2d(2, 2), | |
| nn.Dropout(0.25) | |
| ) | |
| self.fc_layers = nn.Sequential( | |
| nn.Linear(512 * 8 * 8, 1024), | |
| nn.ReLU(), | |
| nn.Linear(1024, 512), | |
| nn.ReLU(), | |
| nn.Linear(512, 256), | |
| nn.ReLU(), | |
| nn.Linear(256, 128), | |
| nn.ReLU(), | |
| nn.Dropout(0.5), | |
| nn.Linear(128, num_classes) | |
| ) | |
| def forward(self, x): | |
| x = self.conv_layers(x) | |
| x = x.view(x.size(0), -1) | |
| x = self.fc_layers(x) | |
| return x | |
| # Load the model | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| model = custom_brain_tumor_model(num_classes=4) | |
| model.load_state_dict(torch.load("brain_tumor_custom_model.pth", map_location=device)) | |
| model.to(device) | |
| model.eval() | |
| # Transform for images | |
| transform = transforms.Compose([ | |
| transforms.Resize((128, 128)), | |
| transforms.ToTensor(), | |
| transforms.Normalize([0.5], [0.5]) | |
| ]) | |
| class_names = ['glioma', 'meningioma', 'no_tumor', 'pituitary'] | |
| # HF API inference function | |
| def predict(image_bytes): | |
| image = Image.open(io.BytesIO(image_bytes)).convert("L") | |
| image = transform(image).unsqueeze(0).to(device) | |
| with torch.no_grad(): | |
| outputs = model(image) | |
| probabilities = torch.nn.functional.softmax(outputs, dim=1)[0] | |
| predicted_idx = torch.argmax(probabilities).item() | |
| return {"class": class_names[predicted_idx], "confidence": float(probabilities[predicted_idx])} | |
| def __call__(self, inputs): | |
| return predict(inputs) | |