-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
58 lines (43 loc) · 1.52 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
from flask import Flask, request, jsonify
import torch
from torchvision import transforms
from PIL import Image
app = Flask(__name__)
def load_model(model_path,device):
model = torch.load(model_path)
model.to(device)
model.eval()
return model
# get the query image from requests
def get_input():
return request.files['image']
# preprocess image before sending to model
def preprocess_img(img):
preprocess=transforms.Compose([
transforms.Resize(size=256),
transforms.CenterCrop(size=224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])
])
return preprocess(img)
@app.route('/api',methods=['POST'])
def predict():
data = get_input()
with torch.no_grad():
img=Image.open(data).convert('RGB')
inputs=preprocess_img(img).unsqueeze(0)
outputs = model(inputs).to(device)
_, preds = torch.max(outputs, 1)
label=class_labels[preds]
output = {'predicted':label}
return jsonify(output) # return json of output
if __name__ == '__main__':
# define the class names
class_labels =['apple','atm card','cat','banana','bangle','battery','bottle','broom','bulb','calender','camera']
# load the pretrained model
MODEL_PATH='image_classification/models/resnet18.pth'
device = 'cpu'
model = load_model(MODEL_PATH,device)
# run the server
app.run(port=8000, debug=True)