Spaces:
Sleeping
Sleeping
import torch | |
import torch.nn as nn | |
from torchvision import models, transforms | |
from PIL import Image | |
import gradio as gr | |
# Interchanged class order: Cancer is now index 0 | |
class_names = ["Cancer", "Normal", "Malignant"] | |
# Preprocessing for CT scan | |
transform = transforms.Compose([ | |
transforms.Resize((224, 224)), | |
transforms.ToTensor(), | |
transforms.Normalize(mean=[0.485, 0.456, 0.406], | |
std=[0.229, 0.224, 0.225]) | |
]) | |
# Load model architecture | |
def get_model(): | |
model = models.vgg16(pretrained=False) | |
model.classifier[6] = nn.Linear(4096, 3) | |
return model | |
# Load model weights | |
model = get_model() | |
model.load_state_dict(torch.load("distilled_vgg16.pth", map_location=torch.device("cpu"))) | |
model.eval() | |
# Prediction function | |
def predict(img: Image.Image): | |
image = transform(img).unsqueeze(0) | |
with torch.no_grad(): | |
outputs = model(image) | |
probs = torch.softmax(outputs, dim=1)[0] | |
pred_idx = torch.argmax(probs).item() | |
return f"Prediction: {class_names[pred_idx]}\nPlease consult a doctor for further diagnosis." | |
# Gradio UI | |
interface = gr.Interface( | |
fn=predict, | |
inputs=gr.Image(type="pil"), | |
outputs=gr.Textbox(label="Diagnosis"), | |
title="Lung Cancer Detection (VGG16, PyTorch)", | |
description="Upload a CT scan image. This tool will predict if it is Cancer, Normal, or Malignant." | |
) | |
if __name__ == "__main__": | |
interface.launch() | |