Add interface.py
Browse files- interface.py +58 -0
interface.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from transformers import SegformerForImageClassification
|
3 |
+
from torchvision import transforms
|
4 |
+
from PIL import Image
|
5 |
+
import gradio as gr
|
6 |
+
|
7 |
+
# Load Alzheimer's model
|
8 |
+
alzheimers_model = SegformerForImageClassification.from_pretrained('nvidia/mit-b1')
|
9 |
+
alzheimers_model.classifier = torch.nn.Linear(alzheimers_model.classifier.in_features, 4) # 4 classes
|
10 |
+
alzheimers_model.load_state_dict(torch.load('alzheimers_model.pth', map_location=torch.device('cpu')))
|
11 |
+
alzheimers_model.eval()
|
12 |
+
|
13 |
+
# Load Brain Tumor model
|
14 |
+
brain_tumor_model = SegformerForImageClassification.from_pretrained('nvidia/mit-b1')
|
15 |
+
brain_tumor_model.classifier = torch.nn.Linear(brain_tumor_model.classifier.in_features, 4) # 4 classes
|
16 |
+
brain_tumor_model.load_state_dict(torch.load('brain_tumor_model.pth', map_location=torch.device('cpu')))
|
17 |
+
brain_tumor_model.eval()
|
18 |
+
|
19 |
+
# Define transformations
|
20 |
+
transform = transforms.Compose([
|
21 |
+
transforms.Resize((224, 224)),
|
22 |
+
transforms.ToTensor(),
|
23 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
24 |
+
])
|
25 |
+
|
26 |
+
# Prediction function for Alzheimer's
|
27 |
+
def predict_alzheimers(image):
|
28 |
+
image = transform(image).unsqueeze(0)
|
29 |
+
with torch.no_grad():
|
30 |
+
outputs = alzheimers_model(image).logits
|
31 |
+
_, predicted = torch.max(outputs, 1)
|
32 |
+
classes = ['Mild Dementia', 'Moderate Dementia', 'Non Demented', 'Very mild Dementia']
|
33 |
+
return classes[predicted.item()]
|
34 |
+
|
35 |
+
# Prediction function for Brain Tumor
|
36 |
+
def predict_brain_tumor(image):
|
37 |
+
image = transform(image).unsqueeze(0)
|
38 |
+
with torch.no_grad():
|
39 |
+
outputs = brain_tumor_model(image).logits
|
40 |
+
_, predicted = torch.max(outputs, 1)
|
41 |
+
classes = ['glioma', 'meningioma', 'notumor', 'pituitary']
|
42 |
+
return classes[predicted.item()]
|
43 |
+
|
44 |
+
def predict(image, model_type):
|
45 |
+
if model_type == "Alzheimer's":
|
46 |
+
return predict_alzheimers(image)
|
47 |
+
elif model_type == "Brain Tumor":
|
48 |
+
return predict_brain_tumor(image)
|
49 |
+
|
50 |
+
interface = gr.Interface(
|
51 |
+
fn=predict,
|
52 |
+
inputs=[gr.Image(type="pil"), gr.Dropdown(["Alzheimer's", "Brain Tumor"])],
|
53 |
+
outputs=gr.Textbox(),
|
54 |
+
title="MRI Scan Classification",
|
55 |
+
description="Upload an MRI scan and select the type of classification."
|
56 |
+
)
|
57 |
+
|
58 |
+
interface.launch()
|