Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import torch
|
3 |
+
import torch.nn.functional as F
|
4 |
+
from torchvision import transforms
|
5 |
+
from PIL import Image
|
6 |
+
from model import load_model
|
7 |
+
import matplotlib.pyplot as plt
|
8 |
+
import numpy as np
|
9 |
+
from thop import profile
|
10 |
+
import io
|
11 |
+
|
12 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
13 |
+
|
14 |
+
models_cache = {}
|
15 |
+
|
16 |
+
transform = transforms.Compose([
|
17 |
+
transforms.Resize((224,224)),
|
18 |
+
transforms.ToTensor(),
|
19 |
+
transforms.Normalize(mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225])
|
20 |
+
])
|
21 |
+
|
22 |
+
class_names = [
|
23 |
+
'Glioma Tumor',
|
24 |
+
'Meningioma Tumor',
|
25 |
+
'No Tumor',
|
26 |
+
'Pituitary Tumor'
|
27 |
+
]
|
28 |
+
|
29 |
+
def calculate_performance(model):
|
30 |
+
model.eval()
|
31 |
+
dummy = torch.randn(1,3,224,224).to(device)
|
32 |
+
flops, params = profile(model, inputs=(dummy,), verbose=False)
|
33 |
+
params_m = round(params/1e6,2)
|
34 |
+
flops_b = round(flops/1e9,2)
|
35 |
+
import time
|
36 |
+
start = time.time()
|
37 |
+
_ = model(dummy.cpu())
|
38 |
+
cpu_ms = round((time.time() - start)*1000,2)
|
39 |
+
if device.type == 'cuda':
|
40 |
+
start_event = torch.cuda.Event(enable_timing=True)
|
41 |
+
end_event = torch.cuda.Event(enable_timing=True)
|
42 |
+
start_event.record()
|
43 |
+
_ = model(dummy)
|
44 |
+
end_event.record()
|
45 |
+
torch.cuda.synchronize()
|
46 |
+
gpu_ms = round(start_event.elapsed_time(end_event),2)
|
47 |
+
else:
|
48 |
+
gpu_ms = None
|
49 |
+
return {'params_million':params_m, 'flops_billion':flops_b, 'cpu_ms':cpu_ms, 'gpu_ms':gpu_ms}
|
50 |
+
|
51 |
+
def predict_and_monitor(version, image):
|
52 |
+
try:
|
53 |
+
if version not in models_cache:
|
54 |
+
models_cache[version] = load_model(version, device)
|
55 |
+
model = models_cache[version]
|
56 |
+
|
57 |
+
if image is None:
|
58 |
+
raise gr.Error("Görsel yüklenmedi.")
|
59 |
+
img = image.convert("RGB")
|
60 |
+
tensor = transform(img).unsqueeze(0).to(device)
|
61 |
+
|
62 |
+
with torch.no_grad():
|
63 |
+
logits = model(tensor)
|
64 |
+
probs = F.softmax(logits, dim=1)[0]
|
65 |
+
|
66 |
+
pred_dict = {class_names[i]: round(float(probs[i]),4) for i in range(len(class_names))}
|
67 |
+
metrics = calculate_performance(model)
|
68 |
+
|
69 |
+
top1 = max(pred_dict, key=pred_dict.get)
|
70 |
+
buf = io.BytesIO()
|
71 |
+
plt.figure(figsize=(3,3))
|
72 |
+
plt.imshow(img)
|
73 |
+
plt.title(f"{top1}: {pred_dict[top1]*100:.1f}%")
|
74 |
+
plt.axis('off')
|
75 |
+
plt.savefig(buf, format='png')
|
76 |
+
plt.close()
|
77 |
+
buf.seek(0)
|
78 |
+
buf_image = Image.open(buf)
|
79 |
+
return pred_dict, metrics, buf_image
|
80 |
+
except Exception as e:
|
81 |
+
raise gr.Error(f"Prediction Error: {e}")
|
82 |
+
|
83 |
+
with gr.Blocks() as demo:
|
84 |
+
gr.Markdown("Tumor Diagnosis with Vbai-TS 2.1(f,c)")
|
85 |
+
with gr.Row():
|
86 |
+
version = gr.Radio(['f','c'], value='c', label="Model Version | f => Fastest, c => Classic")
|
87 |
+
image_in = gr.Image(type="pil", label="MRI or fMRI Image")
|
88 |
+
with gr.Row():
|
89 |
+
preds = gr.JSON(label="Prediction Probabilities")
|
90 |
+
stats = gr.JSON(label="Performance Metrics")
|
91 |
+
plot = gr.Image(label="Prediction")
|
92 |
+
btn = gr.Button("Run")
|
93 |
+
btn.click(fn=predict_and_monitor, inputs=[version, image_in], outputs=[preds, stats, plot])
|
94 |
+
|
95 |
+
if __name__ == '__main__':
|
96 |
+
demo.launch()
|