File size: 1,519 Bytes
f5f7b11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import torch
import torch.nn as nn
from torchvision import transforms, models
from PIL import Image
import gradio as gr

# === Load trained model ===
model = models.resnet18()
in_features = model.fc.in_features
model.fc = nn.Sequential(
    nn.Linear(in_features, 256),
    nn.ReLU(),
    nn.Dropout(0.4),
    nn.Linear(256, 2)
)
model.load_state_dict(torch.load("tumor_model.pth", map_location=torch.device("cpu")))
model.eval()

# === Transform (same as validation) ===
transform = transforms.Compose([
    transforms.Lambda(lambda x: x.convert('RGB')),
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
])

# === Prediction Function ===
def predict(image):
    image = Image.fromarray(image)
    input_tensor = transform(image).unsqueeze(0)
    with torch.no_grad():
        outputs = model(input_tensor)
        _, pred = torch.max(outputs, 1)
        prob = torch.softmax(outputs, dim=1)[0][pred.item()].item()
        label = "Tumor: Yes" if pred.item() == 1 else "Tumor: No"
        return f"{label} ({prob * 100:.2f}%)"

# === Gradio Interface (No examples) ===
interface = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="numpy", label="Upload Brain Scan"),
    outputs=gr.Label(label="Prediction"),
    title="🧠 Tumor Detection",
    description="Upload a brain MRI image to detect if a tumor is present (Yes or No)."
)

if __name__ == "__main__":
    interface.launch()