Create inference.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import torchimport torch.nn as nnfrom torchvision import transformsfrom PIL import Imageimport 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 modeldevice = 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 imagestransform = transforms.Compose([ transforms.Resize((128, 128)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5])])
class_names = ['glioma', 'meningioma', 'no_tumor', 'pituitary']
# HF API inference functiondef 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)inference.pyAdded+76