-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler.py
131 lines (97 loc) · 2.89 KB
/
handler.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
try:
import unzip_requirements
except FileNotFoundError:
pass
except ImportError:
pass
import os
import json
import logging
from pmip.data import load_from_s3_and_unpickle, get_latest_s3_dateint
def get_model(model_id=None, model=None):
latest_model_id = get_latest_s3_dateint(
datadir='models',
bucket=os.getenv('BUCKET')
)
if model_id is not None or model is None or model_id != latest_model_id:
latest_model = load_from_s3_and_unpickle(
filename='model.pkl',
subdirectory=f'models/{latest_model_id}',
bucket=os.getenv('BUCKET')
)
return latest_model_id, latest_model
model_id, model = get_model()
def hello(event, context):
body = {
"message": "Go Serverless v1.0! Your function executed successfully!",
"input": event
}
response = {
"statusCode": 200,
"body": json.dumps(body)
}
return response
# Use this code if you don't use the http event with the LAMBDA-PROXY
# integration
"""
return {
"message": "Go Serverless v1.0! Your function executed successfully!",
"event": event
}
"""
def healthcheck(event, context):
body = {
"status": "ok"
}
response = {
"statusCode": 200,
"body": json.dumps(body)
}
return response
def model_info(event, context):
body = {
"model_id": model_id
}
response = {
"statusCode": 200,
"body": json.dumps(body)
}
return response
def predict(event, context):
request_data = json.loads(event['body'])
if 'queryStringParameters' in event:
if 'flavor' in event['queryStringParameters']:
flavor = event['queryStringParameters']['flavor']
else:
flavor = None
if 'comments' not in request_data:
logging.error("You must provide a list of comments in the data payload")
raise Exception("You must provide a list of comments in the data payload")
return
if flavor is None or flavor == 'class':
val = model.predict(request_data['comments'])
prediction = [{'class': int(s)} for s in val]
elif flavor == 'probability':
val = model.predict_proba(request_data['comments'])
prediction = [{'probability': list(s)} for s in val]
else:
logging.error(f"Unknown type {flavor}")
raise Exception(f"Unknown type {flavor}")
return
body = {
'prediction': prediction
}
response = {
'statusCode': 200,
'body': json.dumps(body)
}
return response
def get_test(event, context):
val = model.predict(["Check it out this free stuff!!!", "I take issue with your characterization."])
prediction = [{'class': int(s)} for s in val]
body = {'prediction': prediction}
response = {
'statusCode': 200,
'body': json.dumps(body)
}
return response