-
Notifications
You must be signed in to change notification settings - Fork 58
/
server.py
448 lines (371 loc) · 14 KB
/
server.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
"""HTTP API implementation.
"""
import sys
from docopt import docopt
from flask import Flask
from flask import make_response
from flask import request
import numpy as np
import ujson
from werkzeug.exceptions import BadRequest
from . import __version__
from .fit import activate as activate_base
from .fit import fit as fit_base
from .interfaces import PredictError
from .util import args_from_config
from .util import get_config
from .util import get_metadata
from .util import initialize_config
from .util import logger
from .util import memory_usage_psutil
from .util import PluggableDecorator
from .util import process_store
from .util import run_job
from .util import resolve_dotted_name
app = Flask(__name__)
def make_ujson_response(obj, status_code=200):
"""Encodes the given *obj* to json and wraps it in a response.
:return:
A Flask response.
"""
json_encoded = ujson.encode(obj, ensure_ascii=False, double_precision=-1)
resp = make_response(json_encoded)
resp.mimetype = 'application/json'
resp.content_type = 'application/json; charset=utf-8'
resp.status_code = status_code
return resp
class PredictService:
"""A default :class:`palladium.interfaces.PredictService`
implementation.
Aims to work out of the box for the most standard use cases.
Allows overriding of specific parts of its logic by using granular
methods to compose the work.
"""
types = {
'float': float,
'int': int,
'str': str,
'bool': lambda x: x.lower() == 'true',
}
def __init__(
self,
mapping,
params=(),
entry_point='/predict',
decorator_list_name='predict_decorators',
predict_proba=False,
unwrap_sample=False,
**kwargs
):
"""
:param mapping:
A list of query parameters and their type that should be
included in the request. These will be processed in the
:meth:`sample_from_data` method to construct a sample
that can be used for prediction. An example that expects
two request parameters called ``pos`` and ``neg`` that are
both of type str::
{ ...
'mapping': [('pos', 'str'), ('neg', 'str')]
... }
:param params:
Similarly to *mapping*, this is a list of name and type of
parameters that will be passed to the model's
:meth:`~palladium.interfaces.Model.predict` method as keyword
arguments.
:param predict_proba:
Instead of returning a single class (the default), when
*predict_proba* is set to true, the result will instead
contain a list of class probabilities.
:param unwrap_sample:
When working with text, scikit-learn and others will
sometimes expect the input to be a 1d array of strings
rather than a 2d array. Setting *unwrap_sample* to true
will use this representation.
"""
self.mapping = mapping
self.params = params
self.entry_point = entry_point
self.decorator_list_name = decorator_list_name
self.predict_proba = predict_proba
self.unwrap_sample = unwrap_sample
vars(self).update(kwargs)
def initialize_component(self, config):
create_predict_function(
self.entry_point, self, self.decorator_list_name, config)
def __call__(self, model, request):
try:
return self.do(model, request)
except Exception as e:
return self.response_from_exception(e)
def do(self, model, request):
if request.method == 'GET':
single = True
samples = np.array([self.sample_from_data(model, request.args)])
else:
single = False
samples = []
for data in request.json:
samples.append(self.sample_from_data(model, data))
samples = np.array(samples)
params = self.params_from_data(model, request.args)
y_pred = self.predict(model, samples, **params)
return self.response_from_prediction(y_pred, single=single)
def sample_from_data(self, model, data):
"""Convert incoming sample *data* into a numpy array.
:param model:
The :class:`~Model` instance to use for making predictions.
:param data:
A dict-like with the sample's data, typically retrieved from
``request.args`` or similar.
"""
values = []
for key, type_name in self.mapping:
value_type = self.types[type_name]
values.append(value_type(data[key]))
if self.unwrap_sample:
assert len(values) == 1
return np.array(values[0])
else:
return np.array(values, dtype=object)
def params_from_data(self, model, data):
"""Retrieve additional parameters (keyword arguments) for
``model.predict`` from request *data*.
:param model:
The :class:`~Model` instance to use for making predictions.
:param data:
A dict-like with the parameter data, typically retrieved
from ``request.args`` or similar.
"""
params = {}
for key, type_name in self.params:
value_type = self.types[type_name]
if key in data:
params[key] = value_type(data[key])
elif hasattr(model, key):
params[key] = getattr(model, key)
return params
def predict(self, model, sample, **kwargs):
if self.predict_proba:
return model.predict_proba(sample, **kwargs)
else:
return model.predict(sample, **kwargs)
def response_from_prediction(self, y_pred, single=True):
"""Turns a model's prediction in *y_pred* into a JSON
response.
"""
result = y_pred.tolist()
if single:
result = result[0]
response = {
'metadata': get_metadata(),
'result': result,
}
return make_ujson_response(response, status_code=200)
def response_from_exception(self, exc):
if isinstance(exc, PredictError):
return make_ujson_response({
'metadata': get_metadata(
error_code=exc.error_code,
error_message=exc.error_message,
status="ERROR"
)
}, status_code=500)
elif isinstance(exc, BadRequest):
return make_ujson_response({
'metadata': get_metadata(
error_code=-1,
error_message="BadRequest: {}".format(exc.args),
status="ERROR"
)
}, status_code=400)
else:
logger.exception("Unexpected error")
return make_ujson_response({
'metadata': get_metadata(
error_code=-1,
error_message="{}: {}".format(
exc.__class__.__name__, str(exc)),
status="ERROR"
)
}, status_code=500)
def predict(model_persister, predict_service):
try:
model = model_persister.read()
response = predict_service(model, request)
except Exception as exc:
logger.exception("Unexpected error")
response = make_ujson_response({
"status": "ERROR",
"error_code": -1,
"error_message": "{}: {}".format(exc.__class__.__name__, str(exc)),
}, status_code=500)
return response
@app.route('/alive')
@PluggableDecorator('alive_decorators')
@args_from_config
def alive(alive=None):
if alive is None:
alive = {}
mem, mem_vms = memory_usage_psutil()
info = {
'memory_usage': mem, # rss, resident set size
'memory_usage_vms': mem_vms, # vms, virtual memory size
'palladium_version': __version__,
}
info['service_metadata'] = get_config().get('service_metadata', {})
status_code = 200
for attr in alive.get('process_store_required', ()):
obj = process_store.get(attr)
if obj is not None:
obj_info = {}
obj_info['updated'] = process_store.mtime[attr].isoformat()
if hasattr(obj, '__metadata__'):
obj_info['metadata'] = obj.__metadata__
info[attr] = obj_info
else:
info[attr] = "N/A"
status_code = 503
info['process_metadata'] = process_store['process_metadata']
return make_ujson_response(info, status_code=status_code)
def create_predict_function(
route, predict_service, decorator_list_name, config):
"""Creates a predict function and registers it to
the Flask app using the route decorator.
:param str route:
Path of the entry point.
:param palladium.interfaces.PredictService predict_service:
The predict service to be registered to this entry point.
:param str decorator_list_name:
The decorator list to be used for this predict service. It is
OK if there is no such entry in the active Palladium config.
:return:
A predict service function that will be used to process
predict requests.
"""
model_persister = config.get('model_persister')
@app.route(route, methods=['GET', 'POST'], endpoint=route)
@PluggableDecorator(decorator_list_name)
def predict_func():
return predict(model_persister, predict_service)
return predict_func
def devserver_cmd(argv=sys.argv[1:]): # pragma: no cover
"""\
Serve the web API for development.
Usage:
pld-devserver [options]
Options:
-h --help Show this screen.
--host=<host> The host to use [default: 0.0.0.0].
--port=<port> The port to use [default: 5000].
--debug=<debug> Whether or not to use debug mode [default: 0].
"""
arguments = docopt(devserver_cmd.__doc__, argv=argv)
initialize_config()
app.run(
host=arguments['--host'],
port=int(arguments['--port']),
debug=int(arguments['--debug']),
)
class PredictStream:
"""A class that helps make predictions through stdin and stdout.
"""
def __init__(self):
self.model = get_config()['model_persister'].read()
self.predict_service = get_config()['predict_service']
def process_line(self, line):
predict_service = self.predict_service
datas = ujson.loads(line)
samples = [predict_service.sample_from_data(self.model, data)
for data in datas]
samples = np.array(samples)
params = predict_service.params_from_data(self.model, datas[0])
return predict_service.predict(self.model, samples, **params)
def listen(self, io_in, io_out, io_err):
"""Listens to provided io stream and writes predictions
to output. In case of errors, the error stream will be used.
"""
for line in io_in:
if line.strip().lower() == 'exit':
break
try:
y_pred = self.process_line(line)
except Exception as e:
io_out.write('[]\n')
io_err.write(
"Error while processing input row: {}"
"{}: {}\n".format(line, type(e), e))
io_err.flush()
else:
io_out.write(ujson.dumps(y_pred.tolist()))
io_out.write('\n')
io_out.flush()
def stream_cmd(argv=sys.argv[1:]): # pragma: no cover
"""\
Start the streaming server, which listens to stdin, processes line
by line, and returns predictions.
The input should consist of a list of json objects, where each object
will result in a prediction. Each line is processed in a batch.
Example input (must be on a single line):
[{"sepal length": 1.0, "sepal width": 1.1, "petal length": 0.7,
"petal width": 5}, {"sepal length": 1.0, "sepal width": 8.0,
"petal length": 1.4, "petal width": 5}]
Example output:
["Iris-virginica","Iris-setosa"]
An input line with the word 'exit' will quit the streaming server.
Usage:
pld-stream [options]
Options:
-h --help Show this screen.
"""
docopt(stream_cmd.__doc__, argv=argv)
initialize_config()
stream = PredictStream()
stream.listen(sys.stdin, sys.stdout, sys.stderr)
@app.route('/list')
@PluggableDecorator('list_decorators')
@args_from_config
def list(model_persister):
info = {
'models': model_persister.list_models(),
'properties': model_persister.list_properties(),
}
return make_ujson_response(info)
@PluggableDecorator('server_fit_decorators')
@args_from_config
def fit():
param_converters = {
'persist': lambda x: x.lower() in ('1', 't', 'true'),
'activate': lambda x: x.lower() in ('1', 't', 'true'),
'evaluate': lambda x: x.lower() in ('1', 't', 'true'),
'persist_if_better_than': float,
}
params = {
name: typ(request.form[name])
for name, typ in param_converters.items()
if name in request.form
}
thread, job_id = run_job(fit_base, **params)
return make_ujson_response({'job_id': job_id}, status_code=200)
@PluggableDecorator('update_model_cache_decorators')
@args_from_config
def update_model_cache(model_persister):
method = getattr(model_persister, 'update_cache', None)
if method is not None:
thread, job_id = run_job(model_persister.update_cache)
return make_ujson_response({'job_id': job_id}, status_code=200)
else:
return make_ujson_response({}, status_code=503)
@PluggableDecorator('activate_decorators')
def activate():
model_version = int(request.form['model_version'])
try:
activate_base(model_version=model_version)
except LookupError:
return make_ujson_response({}, status_code=503)
else:
return list()
def add_url_rule(rule, endpoint=None, view_func=None, app=app, **options):
if isinstance(view_func, str):
view_func = resolve_dotted_name(view_func)
app.add_url_rule(rule, endpoint=endpoint, view_func=view_func, **options)