-
Notifications
You must be signed in to change notification settings - Fork 0
/
infernce2.py
105 lines (86 loc) · 3.38 KB
/
infernce2.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import json
import logging
import sys
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import torchvision.transforms as transforms
from PIL import Image
import io
import requests
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler(sys.stdout))
JSON_CONTENT_TYPE = 'application/json'
JPEG_CONTENT_TYPE = 'image/jpeg'
# Based on https://github.com/pytorch/examples/blob/master/mnist/main.py
def Net():
model = models.resnet50(pretrained=True)
for param in model.parameters():
param.requires_grad = False
model.fc = nn.Sequential(
nn.Linear(2048, 128),
nn.ReLU(inplace=True),
nn.Linear(128, 133))
return model
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def model_fn(model_dir):
print("In model_fn. Model directory is -")
print(model_dir)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = Net().to(device)
with open(os.path.join(model_dir, "model.pth"), "rb") as f:
print("Loading the dog-classifier model")
checkpoint = torch.load(f , map_location =device)
model.load_state_dict(checkpoint)
print('MODEL-LOADED')
logger.info('model loaded successfully')
model.eval()
return model
def input_fn(request_body, content_type=JPEG_CONTENT_TYPE):
logger.info('Deserializing the input data.')
# process an image uploaded to the endpoint
#if content_type == JPEG_CONTENT_TYPE: return io.BytesIO(request_body)
logger.debug(f'Request body CONTENT-TYPE is: {content_type}')
logger.debug(f'Request body TYPE is: {type(request_body)}')
if content_type == JPEG_CONTENT_TYPE: return Image.open(io.BytesIO(request_body))
logger.debug('SO loded JPEG content')
# process a URL submitted to the endpoint
if content_type == JSON_CONTENT_TYPE:
#img_request = requests.get(url)
logger.debug(f'Request body is: {request_body}')
request = json.loads(request_body)
logger.debug(f'Loaded JSON object: {request}')
url = request['url']
img_content = requests.get(url).content
return Image.open(io.BytesIO(img_content))
raise Exception('Requested unsupported ContentType in content_type: {}'.format(content_type))
# inference
def predict_fn(input_object, model):
logger.info('In predict fn')
test_transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
])
logger.info("transforming input")
input_object=test_transform(input_object)
with torch.no_grad():
logger.info("Calling model")
prediction = model(input_object.unsqueeze(0))
return prediction
'''
# postprocess
def output_fn(predictions, content_type):
assert content_type == "application/json"
res = predictions.cpu().numpy().tolist()
return json.dumps(res)
# Serialize the prediction result into the desired response content type
def output_fn(prediction, accept=JSON_CONTENT_TYPE):
logger.info('Serializing the generated output.')
if accept == JSON_CONTENT_TYPE:
logger.debug(f'Returning response {json.dumps(prediction)}')
return json.dumps(prediction), accept
raise Exception('Requested unsupported ContentType in Accept: {}'.format(accept))
'''