-
Notifications
You must be signed in to change notification settings - Fork 14
/
server.py
368 lines (300 loc) · 11.1 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
"""Server that handles all the requests for Net2Vis frontend."""
import os
import json
import zipfile
from datetime import datetime
from shutil import copyfile
import cairosvg
from flask import Flask, send_file, request, jsonify
from translate.translate_keras import translate_keras
from translate.graph import Graph
app = Flask(__name__)
ok_status = 200
json_type = {'ContentType': 'application/json'}
text_type = {'ContentType': 'text/plain'}
##################
# Helper Functions
##################
def make_jsonifyable(network):
"""Convert the Network to be sendable in JSON.
Arguments:
network {object} -- the network description to be converted
Returns:
object -- json description of the network
"""
replace_references(network)
processed = []
for i in range(len(network.layers)):
layer = network.layers[i]
lay = layer.__dict__
layer_dict = {
'name': layer.type,
'id': i,
'properties': lay
}
processed.append(layer_dict)
return processed
def replace_references(net):
"""Replace the References to other objects with indices.
Arguments:
net {object} -- the network for which references are to be replaced
"""
for layer in net.layers:
inp = []
outp = []
for layer_input in layer.input:
for i in range(len(net.layers)):
if net.layers[i] == layer_input:
inp.append(i)
layer.input = inp
for output in layer.output:
for i in range(len(net.layers)):
if net.layers[i] == output:
outp.append(i)
layer.output = outp
def check_exists(identifier):
"""Check if the desired model already exists.
Arguments:
identifier {String} -- the id of the network currently requested
"""
if not os.path.exists('models'):
os.mkdir('models')
if not os.path.exists(os.path.join('models', identifier)):
os.mkdir(os.path.join('models', identifier))
os.mkdir(os.path.join('models', identifier, 'visualizations'))
copyfile(os.path.join('default', 'model_current.py'),
os.path.join('models', identifier, 'model_current.py'))
copyfile(os.path.join('default', 'layer_types_current.json'),
os.path.join('models', identifier, 'layer_types_current.json'))
copyfile(os.path.join('default', 'preferences.json'),
os.path.join('models', identifier, 'preferences.json'))
copyfile(os.path.join('default', 'groups.json'),
os.path.join('models', identifier, 'groups.json'))
copyfile(os.path.join('default', 'legend_preferences.json'),
os.path.join('models', identifier, 'legend_preferences.json'))
def zipdir(path, ziph):
"""Zip a folder.
Arguments:
path {String} -- Path to the folder to be zipped
ziph {object} -- Zip file handle to be used for this process
"""
for root, _, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file), arcname=file)
def save_and_convert_svgs(base_path, json_content):
"""Save and convert the svg files into PDFs
Arguments:
base_path {String} -- The base path for this operation to be executed at
json_content {object} -- The json content of the network
"""
file = open(os.path.join(base_path, 'graph.svg'), 'w')
file.write(json_content['graph'])
file.flush()
file.close()
cairosvg.svg2pdf(url=os.path.join(base_path, 'graph.svg'),
write_to=os.path.join(base_path, 'graph.pdf'))
file = open(os.path.join(base_path, 'legend.svg'), 'w')
file.write(json_content['legend'])
file.flush()
file.close()
cairosvg.svg2pdf(url=os.path.join(base_path, 'legend.svg'),
write_to=os.path.join(base_path, 'legend.pdf'))
def backup_download_content(identifier):
"""Backup the content that is downloaded for use in the paper.
Arguments:
identifier {String} -- The identifier for this network
"""
date_time = datetime.now()
base_location = os.path.join('models', identifier)
save_location = os.path.join(base_location,
date_time.strftime('%Y%m%d%H%M%S'))
if not os.path.exists(save_location):
os.mkdir(save_location)
copyfile(os.path.join(base_location, 'model_current.py'),
os.path.join(save_location, 'model_current.py'))
copyfile(os.path.join(base_location, 'visualizations.zip'),
os.path.join(save_location, 'visualizations.zip'))
###############
# Basic Serving
###############
@app.route('/api/get_network/<identifier>')
def get_network(identifier):
"""Get the Network.
Arguments:
identifier {String} -- the identifier for the requested network
Returns:
object -- a http response containing the network as json
"""
check_exists(identifier)
graph = translate_keras(os.path.join('models', identifier,
'model_current.py'))
if isinstance(graph, Graph):
net = {'layers': make_jsonifyable(graph)}
result = jsonify({'success': True, 'data': net})
else:
result = jsonify({'success': False, 'data': graph})
return result, ok_status, json_type
@app.route('/api/get_code/<identifier>')
def get_code(identifier):
"""Get the Code.
Arguments:
identifier {String} -- the identifier for the requested network
Returns:
object -- a http response containing the code for the network
"""
check_exists(identifier)
with open(os.path.join('models', identifier, 'model_current.py'),
'r') as myfile:
keras_code = myfile.read()
return keras_code, ok_status, text_type
@app.route('/api/update_code/<identifier>', methods=['POST'])
def update_code(identifier):
"""Update the Code.
Arguments:
identifier {String} -- the identifier for the requested network
Returns:
object -- a http response signaling the change worked
"""
check_exists(identifier)
content = request.data
file = open(os.path.join('models', identifier, 'model_current.py'), 'w')
file.write(content.decode("utf-8"))
return content, ok_status, text_type
@app.route('/api/get_layer_types/<identifier>')
def get_layer_types(identifier):
"""Get the Layer_Types.
Arguments:
identifier {String} -- the identifier for the requested network
Returns:
object -- a http response containing the layer types in the model
"""
check_exists(identifier)
with open(os.path.join('models', identifier, 'layer_types_current.json'),
'r') as myfile:
layer_types = myfile.read()
return layer_types, ok_status, text_type
@app.route('/api/update_layer_types/<identifier>', methods=['POST'])
def update_layer_types(identifier):
"""Update the Layer_Types.
Arguments:
identifier {String} -- the identifier for the requested network
Returns:
object -- a http response signaling if the change was successful
"""
check_exists(identifier)
content = request.data
file = open(os.path.join('models', identifier, 'layer_types_current.json'),
'w')
file.write(content.decode("utf-8"))
return content, ok_status, text_type
@app.route('/api/get_preferences/<identifier>')
def get_preferences(identifier):
"""Get the Preferences.
Arguments:
identifier {String} -- the identifier for the requested network
Returns:
object -- a http response containing the visualization preferences
"""
check_exists(identifier)
with open(os.path.join('models', identifier, 'preferences.json'),
'r') as myfile:
preferences = myfile.read()
return preferences, ok_status, text_type
@app.route('/api/update_preferences/<identifier>', methods=['POST'])
def update_preferences(identifier):
"""Update the Preferences.
Arguments:
identifier {String} -- the identifier for the requested network
Returns:
object -- a http response signaling if the change was successful
"""
check_exists(identifier)
content = request.data
file = open(os.path.join('models', identifier, 'preferences.json'),
'w')
file.write(content.decode("utf-8"))
return content, ok_status, text_type
@app.route('/api/get_groups/<identifier>')
def get_groups(identifier):
"""Get the Groups.
Arguments:
identifier {String} -- the identifier for the requested network
Returns:
object -- a http response containing the groups for the model
"""
check_exists(identifier)
with open(os.path.join('models', identifier, 'groups.json'), 'r') as myfile:
groups = myfile.read()
return groups, ok_status, text_type
@app.route('/api/update_groups/<identifier>', methods=['POST'])
def update_groups(identifier):
"""Update the Groups.
Arguments:
identifier {String} -- the identifier for the requested network
Returns:
object -- a http response signaling if the change was successful
"""
check_exists(id)
content = request.data
file = open(os.path.join('models', identifier, 'groups.json'), 'w')
file.write(content.decode("utf-8"))
return content, ok_status, text_type
@app.route('/api/get_legend_preferences/<identifier>')
def get_legend_preferences(identifier):
"""Get the Preferences.
Arguments:
identifier {String} -- the identifier for the requested network
Returns:
object -- a http response containing the legend preferences for the model
"""
check_exists(identifier)
with open(os.path.join('models', identifier, 'legend_preferences.json'),
'r') as myfile:
preferences = myfile.read()
return preferences, ok_status, text_type
@app.route('/api/update_legend_preferences/<identifier>', methods=['POST'])
def update_legend_preferences(identifier):
"""Update the Preferences.
Arguments:
identifier {String} -- the identifier for the requested network
Returns:
object -- a http response signaling if the change was successful
"""
check_exists(identifier)
content = request.data
file = open(os.path.join('models', identifier, 'legend_preferences.json'),
'w')
file.write(content.decode("utf-8"))
return content, ok_status, text_type
@app.route('/api/process_vis/<identifier>', methods=['POST'])
def process_vis(identifier):
"""Pack and transform the visualization
Arguments:
identifier {String} -- the identifier for the requested network
Returns:
object -- a http response containing the zip file with the visualizations
"""
check_exists(identifier)
content = request.data
# Get the Json representation of the Request Body
json_content = json.loads(content)
# Base_Path for Visualizations
base_path = os.path.join('models', identifier, 'visualizations')
# Save and convert the svg files into PDFs
save_and_convert_svgs(base_path, json_content)
# Create a Zip File
zipf = zipfile.ZipFile(os.path.join('models', identifier,
'visualizations.zip'), 'w',
zipfile.ZIP_DEFLATED)
# Zip a directory into this file
zipdir(base_path, zipf)
zipf.close()
# Save the downloaded state for evaluation
backup_download_content(identifier)
# Send the Zip back to the frontend
return send_file(os.path.join('models', identifier, 'visualizations.zip'),
mimetype='zip',
attachment_filename='visualizations.zip',
as_attachment=True)
if __name__ == '__main__':
app.run(debug=True)