-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathapp.py
59 lines (48 loc) · 1.97 KB
/
app.py
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
50
51
52
53
54
55
56
57
58
59
from io import BytesIO
from torch import argmax, load
from torch import device as DEVICE
from torch.cuda import is_available
from torch.nn import Sequential, Linear, SELU, Dropout, LogSigmoid
from PIL import Image
from torchvision.transforms import Compose, ToTensor, Resize
from torchvision.models import resnet50
from flask import Flask, jsonify, request
app = Flask(__name__)
LABELS = ['None', 'Meningioma', 'Glioma', 'Pitutary']
device = "cuda" if is_available() else "cpu"
resnet_model = resnet50(pretrained=True)
for param in resnet_model.parameters():
param.requires_grad = True
n_inputs = resnet_model.fc.in_features
resnet_model.fc = Sequential(Linear(n_inputs, 2048),
SELU(),
Dropout(p=0.4),
Linear(2048, 2048),
SELU(),
Dropout(p=0.4),
Linear(2048, 4),
LogSigmoid())
for name, child in resnet_model.named_children():
for name2, params in child.named_parameters():
params.requires_grad = True
resnet_model.to(device)
resnet_model.load_state_dict(load('./models/bt_resnet50_model.pt', map_location=DEVICE(device)))
resnet_model.eval()
def preprocess_image(image_bytes):
transform = Compose([Resize((512, 512)), ToTensor()])
img = Image.open(BytesIO(image_bytes))
return transform(img).unsqueeze(0)
def get_prediction(image_bytes):
tensor = preprocess_image(image_bytes=image_bytes)
y_hat = resnet_model(tensor.to(device))
class_id = argmax(y_hat.data, dim=1)
return str(int(class_id)), LABELS[int(class_id)]
@app.route('/predict', methods=['POST'])
def predict():
if request.method == 'POST':
file = request.files['file']
img_bytes = file.read()
class_id, class_name = get_prediction(img_bytes)
return jsonify({'class_id': class_id, 'class_name': class_name})
if __name__ == '__main__':
app.run()