-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmanage.py
449 lines (370 loc) · 17.8 KB
/
manage.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
449
from settings import *
from namastox import manage
import json
import os
import tempfile
import shutil
from werkzeug.utils import secure_filename
from flame.manage import action_import
from flame.util.utils import set_repositories
# GET LIST of RA
@app.route(f'{url_base}{version}list',methods=['GET'])
@cross_origin()
def getList():
success, data = manage.action_list(out='json')
if success:
return data
else:
return json.dumps(f'Failed to obtain list of RAs'), 500, {'ContentType':'application/json'}
# GET LIST of steps
@app.route(f'{url_base}{version}steps/<string:ra_name>',methods=['GET'])
@cross_origin()
def getSteps(ra_name):
success, data = manage.action_steps(ra_name, out='json')
if success:
return data
else:
return json.dumps(f'Failed to obtain steps for RA {ra_name}'), 500, {'ContentType':'application/json'}
# GET GENERAL INFO RA
@app.route(f'{url_base}{version}general_info/<string:ra_name>',methods=['GET'])
@cross_origin()
def getGeneralInfo(ra_name):
success, data = manage.action_info(ra_name, out='json')
if success:
return data
else:
return json.dumps(f'Failed to obtain general infor for {ra_name}, with error {data}'), 500, {'ContentType':'application/json'}
# PUT NEW RA
@app.route(f'{url_base}{version}new/<string:ra_name>',methods=['PUT'])
@cross_origin()
def putNew(ra_name):
success, data = manage.action_new(ra_name)
if success:
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
else:
return json.dumps(f'Failed to create new RA {ra_name}, with error {data}'), 500, {'ContentType':'application/json'}
# PUT DELETE RA
@app.route(f'{url_base}{version}delete/<string:ra_name>',methods=['PUT'])
@app.route(f'{url_base}{version}delete/<string:ra_name>/<int:step>',methods=['PUT'])
@cross_origin()
def putKill(ra_name, step=None):
success, data = manage.action_kill(ra_name, step)
if success:
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
else:
# return (f'failed for {ra_name}', 500)
return json.dumps(f'Failed to delete RA {ra_name}, with error {data}'), 500, {'ContentType':'application/json'}
def allowed_attachment(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def allowed_structure(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_STRUCTURE_EXTENSIONS
def allowed_workflow(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_WORKFLOW_EXTENSIONS
def allowed_import(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_IMPORT_EXTENSIONS
# PUT LINK, call this to send a link from the GUI to upload to the backend (RA repository)
@app.route(f'{url_base}{version}link/<string:ra_name>',methods=['POST'])
@cross_origin()
def putLink(ra_name):
# check if the post request has the file part
if 'file' not in request.files:
return json.dumps(f'Failed to upload file, no file information found'), 500, {'ContentType':'application/json'}
file = request.files['file']
# If the user does not select a file, the browser submits an
# empty file without a filename.
if file.filename == '':
return json.dumps(f'Failed to upload file, empty file nama'), 500, {'ContentType':'application/json'}
if file and allowed_attachment(file.filename):
filename = secure_filename(file.filename)
filename = filename.replace (' ','_')
success, data = manage.getRepositoryPath (ra_name)
if not success:
return json.dumps(f'Failed to upload file, unable to access repository'), 500, {'ContentType':'application/json'}
file.save(os.path.join(data, filename))
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
else:
return json.dumps(f'Failed to upload file, incorrect file or file type '), 500, {'ContentType':'application/json'}
# GET LINK
@app.route(f'{url_base}{version}link/<string:ra_name>/<string:link_name>',methods=['GET'])
@cross_origin()
def getLink(ra_name, link_name):
success, repo_path = manage.getRepositoryPath (ra_name)
if success:
link_name = link_name.replace (' ','_')
link_file = os.path.join (repo_path, link_name)
return send_file(link_file, as_attachment=True)
else:
return json.dumps(f'Failed to get link {link_name}, with error {repo_path}'), 500, {'ContentType':'application/json'}
# GET WORKFLOW DEFINITION
@app.route(f'{url_base}{version}workflow/<string:ra_name>',methods=['GET'])
@app.route(f'{url_base}{version}workflow/<string:ra_name>/<int:step>',methods=['GET'])
@cross_origin()
def getWorkflow(ra_name, step=None):
success, workflow_graph = manage.getWorkflow (ra_name, step)
if success:
return json.dumps({'success':True, 'result': workflow_graph}), 200, {'ContentType':'application/json'}
else:
return json.dumps(f'Failed to get workflow for {ra_name}, with error {workflow_graph}'), 500, {'ContentType':'application/json'}
# # PUT CUSTOM WORKFLOW DEFINITION
# @app.route(f'{url_base}{version}custom_workflow/<string:ra_name>',methods=['PUT'])
# @cross_origin()
# def putCustomWorkflow(ra_name, step=None):
# # check if the post request has the file part
# if 'file' not in request.files:
# return json.dumps(f'Failed to upload file, no file information found'), 500, {'ContentType':'application/json'}
# file = request.files['file']
# # If the user does not select a file, the browser submits an
# # empty file without a filename.
# if file.filename == '':
# return json.dumps(f'Failed to upload file, empty file name'), 500, {'ContentType':'application/json'}
# if file and allowed_workflow(file.filename):
# filename = secure_filename(file.filename)
# success, ra_path = manage.getPath (ra_name)
# if not success:
# return json.dumps(f'Failed to upload file, unable to access repository'), 500, {'ContentType':'application/json'}
# file.save(os.path.join(ra_path, filename))
# success, result = manage.setCustomWorkflow (ra_name, filename)
# else:
# return json.dumps(f'Failed to upload file, no file'), 500, {'ContentType':'application/json'}
# return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
# GET SUBSTANCE LIST
@app.route(f'{url_base}{version}substances',methods=['PUT'])
@cross_origin()
def convertSubstances():
# check if the post request has the file part
if 'file' not in request.files:
return json.dumps(f'Failed to upload file, no file information found'), 500, {'ContentType':'application/json'}
file = request.files['file']
if file and allowed_structure(file.filename):
# copy the file to a temporary file in the backend
tempdirname = tempfile.mkdtemp()
filename = secure_filename(file.filename)
structure_path = os.path.join(tempdirname, filename)
file.save(structure_path)
# now call an endpoint which returns a JSON with the structure characteristics
success, substances = manage.convertSubstances(structure_path)
# remove the temp dir
shutil.rmtree(tempdirname)
else:
return json.dumps(f'Failed to convert substances. Format unsuported'), 500, {'ContentType':'application/json'}
if success:
return json.dumps({'success':True, 'result': substances}), 200, {'ContentType':'application/json'}
else:
return json.dumps(f'Failed to convert substances with error {substances}'), 500, {'ContentType':'application/json'}
# EXPORT RA
@app.route(f'{url_base}{version}export/<string:ra_name>/',methods=['GET'])
@cross_origin()
def exportRA(ra_name):
success, export_file = manage.exportRA (ra_name)
if success:
return send_file(export_file, as_attachment=True)
else:
return json.dumps(f'Failed to export {ra_name}'), 500, {'ContentType':'application/json'}
# IMPORT RA
@app.route(f'{url_base}{version}import/',methods=['POST'])
@cross_origin()
def importRA():
# check if the post request has the file part
if 'file' not in request.files:
return json.dumps({"success": False, "error": "Failed to upload file, no file information found"}), 500, {'ContentType':'application/json'}
file = request.files['file']
# If the user does not select a file, the browser submits an
# empty file without a filename.
if file.filename == '':
return json.dumps({"success": False, "error": "Failed to upload file, empty filename"}), 500, {'ContentType':'application/json'}
if file and allowed_import(file.filename):
# copy the file to a temporary file in the backend
tempdirname = tempfile.mkdtemp()
filename = secure_filename(file.filename)
import_path = os.path.join(tempdirname, filename)
file.save(import_path)
# call import with local path pointing to temp dir
success, message = manage.importRA (import_path)
# remove the temp dir
shutil.rmtree(tempdirname)
if not success:
return json.dumps(f'Failed to import file {import_path} with error: {message}'), 500, {'ContentType':'application/json'}
if success:
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
else:
return json.dumps(f'Failed to import {filename}'), 500, {'ContentType':'application/json'}
# EXPORT ATTACHMENTS
@app.route(f'{url_base}{version}attachments/<string:ra_name>/',methods=['GET'])
@cross_origin()
def attachmentsRA(ra_name):
success, attachments_file = manage.attachmentsRA (ra_name)
if success:
return send_file(attachments_file, as_attachment=True)
else:
return json.dumps(f'Failed to obtain attachments for {ra_name}'), 500, {'ContentType':'application/json'}
# RETURN LIST OF LOCALLY ACCESSIBLE MODELS
@app.route(f'{url_base}{version}models/',methods=['GET'])
@cross_origin()
def localModels():
success, models = manage.getLocalModels()
if success :
return models, 200, {'ContentType':'application/json'}
else:
return json.dumps(f'Failed to get list of local models'), 500, {'ContentType':'application/json'}
# RETURN DOCUMENTATION FOR A MODELS
@app.route(f'{url_base}{version}model_documentation/<string:model_name>/<int:model_ver>',methods=['GET'])
@cross_origin()
def modelDocumentation(model_name, model_ver):
success, models = manage.getModelDocumentation(model_name,model_ver)
if success :
return models, 200, {'ContentType':'application/json'}
else:
return json.dumps(f'Failed to get documentation for model {model_name} ver {model_ver}'), 500, {'ContentType':'application/json'}
# PREDICT RA SUBSTANCE USING LIST OF MODELS
@app.route(f'{url_base}{version}predict/<string:ra_name>',methods=['PUT'])
@cross_origin()
def predict(ra_name):
models = []
versions = []
if 'models' in request.form:
models_raw = request.form['models'].strip().split(',')
models = []
for i in models_raw:
if i!='':
models.append(i)
if 'versions' in request.form:
versions_raw = request.form['versions'].strip().split(',')
versions = []
for i in versions_raw:
if i!='':
versions.append(int(i))
if len(models)==0 or len(versions)==0 or len(versions)!=len(models):
return json.dumps(f'Incomplete model information in prediction call'), 500, {'ContentType':'application/json'}
success, results = manage.predictLocalModels(ra_name, models, versions)
if success:
success, results = manage.getLocalModelPrediction(ra_name, results)
if success :
return results, 200, {'ContentType':'application/json'}
else:
return json.dumps(f'Predictions not completed for substance of {ra_name}'), 500, {'ContentType':'application/json'}
else:
return json.dumps(f'Failed to predict substance of {ra_name} with error:, {results}'), 500, {'ContentType':'application/json'}
# PREDICT RA SUBSTANCE USING LIST OF MODELS
@app.route(f'{url_base}{version}inform_name/<string:molname>',methods=['GET'])
@app.route(f'{url_base}{version}inform_casrn/<string:casrn>',methods=['GET'])
@cross_origin()
def inform(molname=None, casrn=None):
success, results = manage.getInfoStructure(molname, casrn)
if success:
# the answer contains an structure like this:
#[
# {
# "activeAssays": 0,
# "averageMass": 68.075,
# "casrn": "110-00-9",
# "compoundId": 646,
# "cpdataCount": 2,
# "dtxcid": "DTXCID20646",
# "dtxsid": "DTXSID6020646",
# "genericSubstanceId": 20646,
# "hasStructureImage": true,
# "id": "FD7EFD3AFDFD6E00FD610A4EFD5C29FDFD2A3D3FFD4E3DFD3925FD39E7FD",
# "inchiKey": "YLQBMQCUIZJEEH-UHFFFAOYSA-N",
# "inchiString": "InChI=1S/C4H4O/c1-2-4-5-3-1/h1-4H\n",
# "isotope": 0,
# "iupacName": "Furan",
# "molFormula": "C4H4O",
# "monoisotopicMass": 68.026214749,
# "multicomponent": 0,
# "percentAssays": 0,
# "preferredName": "Furan",
# "pubchemCid": 8029,
# "pubchemCount": 280,
# "pubmedCount": 919,
# "qcLevel": 1,
# "qcLevelDesc": "Level 1: Expert curated, highest confidence in accuracy and consistency of unique chemical identifiers",
# "relatedStructureCount": 1,
# "relatedSubstanceCount": 1,
# "selected": null,
# "smiles": "O1C=CC=C1",
# "sourcesCount": 230,
# "stereo": 0,
# "totalAssays": 235,
# "toxcastSelect": "0/235"
# }
#]
# the dtxsid can be used to present a link like this
# https://comptox.epa.gov/dashboard/chemical/details/DTXSID4041280
return results, 200, {'ContentType':'application/json'}
else:
return json.dumps(f'Failed to inform mol {molname} with error {results}'), 500, {'ContentType':'application/json'}
# PUT TABLE
@app.route(f'{url_base}{version}table/<string:ra_name>',methods=['POST'])
@cross_origin()
def putTable(ra_name):
# check if the post request has the file part
if 'file' not in request.files:
return json.dumps(f'Failed to upload file, no file information found'), 500, {'ContentType':'application/json'}
file = request.files['file']
# If the user does not select a file, the browser submits an
# empty file without a filename.
if file.filename == '':
return json.dumps(f'Failed to upload file, empty filename'), 500, {'ContentType':'application/json'}
if file and allowed_attachment(file.filename):
filename = secure_filename(file.filename)
filename = filename.replace (' ','_')
success, data = manage.getRepositoryPath (ra_name)
if not success:
return json.dumps(f'Failed to upload file, unable to access repository'), 500, {'ContentType':'application/json'}
pathname = os.path.join(data, filename)
file.save(pathname)
success, values, uncertainties = manage.getTableContents(pathname)
if success:
return json.dumps({'success':True, 'values': values, 'uncertainties': uncertainties}), 200, {'ContentType':'application/json'}
else:
return json.dumps({'success:': False, 'error': f'{values} {uncertainties}'}), 500, {'ContentType':'application/json'}
else:
return json.dumps({'success:': False, 'error': 'Failed to upload file, incorrect file or file type'}), 500, {'ContentType':'application/json'}
# CHANGE REPO
@app.route(f'{url_base}{version}newrepo/<string:newrepo>',methods=['GET'])
@cross_origin()
def changeRepo(newrepo):
if not os.path.isdir(newrepo):
return json.dumps(f'Invalid path'), 500, {'ContentType':'application/json'}
success = set_repositories(newrepo)
if success:
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
else:
return json.dumps({'success':False}), 500, {'ContentType':'application/json'}
# IMPORT MODEL
@app.route(f'{url_base}{version}import_model',methods=['POST'])
@cross_origin()
def importModel():
# check if the post request has the file part
if 'file' not in request.files:
return json.dumps(f'Failed to upload file, no file information found'), 500, {'ContentType':'application/json'}
file = request.files['file']
# If the user does not select a file, the browser submits an
# empty file without a filename.
if file.filename == '':
return json.dumps(f'Failed to upload file, empty filename'), 500, {'ContentType':'application/json'}
if file and allowed_import(file.filename):
filename = secure_filename(file.filename)
filename = filename.replace (' ','_')
data = manage.getModelPath ()
pathname = os.path.join(data, filename)
file.save(pathname)
# success, values, uncertainties = manage.getTableContents(pathname)
success, result = action_import(pathname)
if result.startswith('WARNING: Incompatible libraries'):
success = True
# clean removing the tgz file
try:
os.remove(pathname)
except:
pass
if success:
return json.dumps({'success':True, 'message': result}), 200, {'ContentType':'application/json'}
else:
return json.dumps({'success':False, 'message': result}), 500, {'ContentType':'application/json'}
else:
return json.dumps({'success:': False, 'error': 'no suitable file'}), 500, {'ContentType':'application/json'}