-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathwebapp.py
204 lines (153 loc) · 6.8 KB
/
webapp.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
import os
import json
import tempfile
import zipfile
from flask import Flask, send_file, Response
from moodlemlbackend.processor import estimator
from moodlemlbackend.webapp.access import check_access
from moodlemlbackend.webapp.util import get_request_value, get_file_path
from moodlemlbackend.webapp.util import zipdir
app = Flask(__name__)
# If the MOODLE_MLBACKEND_PYTHON_S3_BUCKET_NAME environment variable is set, we
# use the S3 backend, otherwise the local file system.
#
# Note that there are conditional imports here, and linters might
# complain that they are not right at the top. Those linters should
# relax. What we are doing here is completely fine.
if "MOODLE_MLBACKEND_PYTHON_S3_BUCKET_NAME" in os.environ:
from moodlemlbackend.webapp.s3 import S3, S3_setup_base_dir
storage = S3()
setup_base_dir = S3_setup_base_dir
else:
from moodlemlbackend.webapp.localfs import LocalFS, LocalFS_setup_base_dir
storage = LocalFS()
setup_base_dir = LocalFS_setup_base_dir
# Set MOODLE_MLBACKEND_TEMPDIR to use something other than /tmp for
# temporary storage.
if "MOODLE_MLBACKEND_TEMPDIR" in os.environ:
tempfile.tempdir = os.environ['MOODLE_MLBACKEND_TEMPDIR']
@app.route('/version', methods=['GET'])
def version():
here = os.path.abspath(os.path.dirname(__file__))
# "./web-compat-version" is NOT in the git tree.
# If it exists, the version there is used; otherwise the true
# version is given. This allows versions with interchangeable APIs
# to be substituted for each other, allowing the ML-backend to be
# upgraded at a different cadence than Moodle itself.
# (Moodle makes a strict version check).
for fn in [os.path.join(here, 'web-compat-version'),
os.path.join(here, 'moodlemlbackend', 'VERSION')]:
if os.path.exists(fn):
with open(fn) as f:
return f.read().strip()
@app.route('/training', methods=['POST'])
@check_access
@setup_base_dir(storage, True, True)
def training():
uniquemodelid = get_request_value('uniqueid')
modeldir = storage.get_model_dir('dirhash')
with get_file_path(storage.get_localbasedir(), 'dataset') as dataset:
classifier = estimator.Classifier(uniquemodelid, modeldir, dataset=dataset)
result = classifier.train_dataset(dataset)
return json.dumps(result)
@app.route('/prediction', methods=['POST'])
@check_access
@setup_base_dir(storage, True, True)
def prediction():
uniquemodelid = get_request_value('uniqueid')
modeldir = storage.get_model_dir('dirhash')
with get_file_path(storage.get_localbasedir(), 'dataset') as datasetpath:
classifier = estimator.Classifier(uniquemodelid, modeldir, datasetpath)
result = classifier.predict_dataset(datasetpath)
return json.dumps(result)
@app.route('/evaluation', methods=['POST'])
@check_access
@setup_base_dir(storage, False, False)
def evaluation():
uniquemodelid = get_request_value('uniqueid')
modeldir = storage.get_model_dir('dirhash')
minscore = get_request_value('minscore', pattern='[^0-9.$]')
maxdeviation = get_request_value('maxdeviation', pattern='[^0-9.$]')
niterations = get_request_value('niterations', pattern='[^0-9$]')
trainedmodeldirhash = get_request_value(
'trainedmodeldirhash', exception=False)
if trainedmodeldirhash is not False:
# The trained model dir in the server is namespaced by uniquemodelid
# and the trainedmodeldirhash which determines where should the results
# be stored.
trainedmodeldir = storage.get_model_dir(
'trainedmodeldirhash', fetch_model=True)
else:
trainedmodeldir = False
with get_file_path(storage.get_localbasedir(), 'dataset') as datasetpath:
classifier = estimator.Classifier(uniquemodelid, modeldir, datasetpath)
result = classifier.evaluate_dataset(datasetpath,
float(minscore),
float(maxdeviation),
int(niterations),
trainedmodeldir)
return json.dumps(result)
@app.route('/evaluationlog', methods=['GET'])
@check_access
@setup_base_dir(storage, True, False)
def evaluationlog():
modeldir = storage.get_model_dir('dirhash')
runid = get_request_value('runid', '[^0-9$]')
logsdir = os.path.join(modeldir, 'logs', runid)
zipf = tempfile.NamedTemporaryFile()
zipdir(logsdir, zipf)
return send_file(zipf.name, mimetype='application/zip')
@app.route('/export', methods=['GET'])
@check_access
@setup_base_dir(storage, True, False)
def export():
uniquemodelid = get_request_value('uniqueid')
modeldir = storage.get_model_dir('dirhash')
# We can use a temp directory for the export data
# as we don't need to keep it forever.
tempdir = tempfile.TemporaryDirectory()
classifier = estimator.Classifier(uniquemodelid, modeldir)
exportdir = classifier.export_classifier(tempdir.name)
if exportdir is False:
return Response('There is nothing to export.', 503)
zipf = tempfile.NamedTemporaryFile()
zipdir(exportdir, zipf)
return send_file(zipf.name, mimetype='application/zip')
@app.route('/import', methods=['POST'])
@check_access
@setup_base_dir(storage, False, True)
def import_model():
uniquemodelid = get_request_value('uniqueid')
modeldir = storage.get_model_dir('dirhash')
with get_file_path(storage.get_localbasedir(), 'importzip') as importzippath:
with zipfile.ZipFile(importzippath, 'r') as zipobject:
with tempfile.TemporaryDirectory() as importtempdir:
zipobject.extractall(importtempdir)
classifier = estimator.Classifier(uniquemodelid, modeldir)
classifier.import_classifier(importtempdir)
return 'Ok', 200
@app.route('/deletemodel', methods=['POST'])
@check_access
@setup_base_dir(storage, False, False)
def deletemodel():
# All processing is delegated to delete_dir as it is file system dependant.
storage.delete_dir()
return 'Ok', 200
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--world-visible', action='store_true',
help='Allow connections from beyond localhost')
parser.add_argument('-p', '--port', default=5000, type=int,
help='listen on this port')
parser.add_argument('--debug-mode', action='store_true',
help='enable debug features (unsafe in production)')
args = parser.parse_args()
# --debug-mode shows validation progress in logs
estimator.DEBUG_MODE = args.debug_mode
if not args.world_visible:
app.run(debug=args.debug_mode, port=args.port)
else:
app.run(debug=args.debug_mode, host='0.0.0.0', port=args.port)
if __name__ == '__main__':
main()