-
Notifications
You must be signed in to change notification settings - Fork 41
/
views.py
416 lines (318 loc) · 11.6 KB
/
views.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
import datetime
import os
import time
from flask import current_app as app, Blueprint, jsonify, render_template, abort, send_file, session, request
from flask.helpers import safe_join
from app import utils
import misc_utils
import json
import random
import subprocess
views = Blueprint('views', __name__)
tensorboard = None
def parse_meta_json(metapath):
with open(metapath, 'r') as f:
meta = json.load(f)
state = None
for line in meta:
if 'finishtime' not in line:
if line['gpu'] == '-1':
state = 'cpu'
else:
state = 'cuda:' + line['gpu']
break
else:
state = 'finished'
model = meta[0]['config']['MODEL']['NAME']
acc = 0.
runtime = 0.
for line in meta:
acc = max(acc, line['best_acc'])
if 'finishtime' in line:
runtime += int(line['finishtime']) - int(line['starttime'])
else:
runtime += int(misc_utils.get_time_stamp()) - int(line['starttime'])
runtime = misc_utils.format_time(runtime)
if 'remarks' in meta[0]:
remarks = meta[0]['remarks']
else:
remarks = ''
return {
'state': state,
'model': model,
'acc': acc,
'runtime': runtime,
'remarks': remarks
}
def parse_runs(tag):
template_root = os.path.abspath(os.path.join(app.root_path, '..'))
logroot = os.path.join(template_root, 'logs')
logpath = os.path.join(logroot, tag, 'meta.json')
if not os.path.isfile(logpath):
return []
with open(logpath, 'r') as f:
meta = json.load(f)
runs = []
for line in meta:
run = {
'command': line['command'],
'starttime': misc_utils.get_time_str(line['starttime'], fmt='%Y-%m-%d %H:%M:%S')
}
if 'finishtime' in line:
runtime = int(line['finishtime']) - int(line['starttime'])
else:
runtime = int(misc_utils.get_time_stamp()) - int(line['starttime'])
run['runtime'] = misc_utils.format_time(runtime)
runs.append(run)
return runs
def parse_log(tag):
template_root = os.path.abspath(os.path.join(app.root_path, '..'))
logroot = os.path.join(template_root, 'logs')
logpath = os.path.join(logroot, tag, 'log.txt')
if not os.path.isfile(logpath):
return ''
with open(logpath, 'r') as f:
lines = f.readlines()
option = False
config = False
time_color = '#777777'
for i, line in enumerate(lines):
if option and '===========================================' in line:
option = False
if config and '===========================================' in line or '==================Options==================' in line:
config = False
if line.startswith('[INFO]'):
if option:
pos_equ = line.find('=')
lines[i] = f'<span style="color:{time_color};">' + lines[i][:26] + '</span>' + \
'<span style="color:#457ab2;">' + lines[i][26:pos_equ] + '</span>' + '=' + \
'<span style="color:#262420;">' + lines[i][pos_equ+1:] + '</span>'
elif config:
pos_equ = line.rfind(':')
if pos_equ > 26:
lines[i] = f'<span style="color:{time_color};">' + lines[i][:26] + '</span>' + \
'<span style="color:#457ab2;">' + lines[i][26:pos_equ] + '</span>' + ':' + \
'<span style="color:#262420;">' + lines[i][pos_equ+1:] + '</span>'
else:
lines[i] = ''
elif 'Eva(' in line:
lines[i] = f'<span style="color:{time_color};">' + lines[i][:26] + '</span><span style="color:#981e23;">' + lines[i][26:] + '</span>'
else:
lines[i] = f'<span style="color:{time_color};">' + lines[i][:26] + '</span><span style="color:#262420;">' + lines[i][26:] + '</span>'
else:
lines[i] = '<span style="color:#262420;">' + lines[i] + '</span>'
if 'train_trasforms' in lines[i]:
pos_trans = lines[i].find('train_trasforms')
lines[i] = lines[i][:pos_trans] + '<span style="color:#067106;">train_trasforms:</span>' + lines[i][pos_trans + len('train_trasforms:'):]
if 'val_trasforms' in lines[i]:
pos_trans = lines[i].find('val_trasforms')
lines[i] = lines[i][:pos_trans] + '<span style="color:#067106;">val_trasforms:</span>' + lines[i][pos_trans + len('val_trasforms:'):]
if 'scheduler:' in lines[i]:
pos_trans = lines[i].find('scheduler')
lines[i] = lines[i][:pos_trans] + '<span style="color:#067106;">scheduler:</span>' + lines[i][pos_trans + len('scheduler:'):]
if '==================Options==================' in line:
option = True
if '==================Configs==================' in line:
config = True
lines[i] = lines[i].replace(' ', ' ')
lines = filter(lambda x: x, lines)
log = '<br/>'.join(lines)
return log
def get_meta(dir='logs'):
template_root = os.path.abspath(os.path.join(app.root_path, '..'))
logroot = os.path.join(template_root, dir)
logs = os.listdir(logroot)
logs.sort()
metas = []
for tag in logs:
logpath = os.path.join(logroot, tag, 'meta.json')
meta_line = {
'tag': tag,
'state': '-',
'model': '-',
'acc': '-',
'runtime': '-',
'remarks': ''
}
if os.path.isfile(logpath):
meta_line.update(parse_meta_json(logpath))
metas.append(meta_line)
return metas
def opentensorboard(tag, dir='logs'):
template_root = os.path.abspath(os.path.join(app.root_path, '..'))
logroot = os.path.join(template_root, dir)
logpath = os.path.join(logroot, tag)
global tensorboard
if tensorboard is not None:
return False
cmd = f'tensorboard --logdir {logpath} --host=0.0.0.0'
tensorboard = subprocess.Popen(cmd, shell=True,bufsize = -1, stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
# tensorboard.kill()
return True
def closetensorboard():
cmd = "ps aux|grep tensorboard|grep -v grep |awk '{print $2}'|xargs kill -9"
os.system(cmd)
return True
@views.route('/tensorboardon')
def tensorboardon():
requests = request.args
if 'val' in requests:
dir = 'results'
else:
dir = 'logs'
if 'tag' not in requests:
if opentensorboard('.', dir):
return 'ok'
return 'fail'
tag = requests['tag']
if opentensorboard(tag, dir):
return 'ok'
return 'fail'
@views.route('/tensorboardoff')
def tensorboardoff():
global tensorboard
if closetensorboard():
tensorboard = None
return 'ok'
return 'fail'
@views.route('/api')
def api():
# session.permanent = True
requests = request.args
if 'tag' not in requests:
return jsonify([])
meta = parse_runs(requests['tag'])
return jsonify(meta)
@views.route('/log')
def log():
# session.permanent = True
requests = request.args
if 'tag' not in requests:
return ''
log = parse_log(requests['tag'])
return log
def del_one_tag(tag):
template_root = os.path.abspath(os.path.join(app.root_path, '..'))
paths = ['checkpoints', 'logs', 'results']
trashtmp = utils.get_time_stamp() + f'{random.randint(0,1000):04d}'
for path in paths:
tmp = os.path.join('_.trash', trashtmp, path)
misc_utils.try_make_dir(tmp)
p = os.path.join(template_root, path, tag)
if os.path.isdir(p):
command = 'mv %s %s' % (p, tmp)
os.system(command)
@views.route('/del', methods=['POST'])
def deltags():
tag = request.form['tag']
# session.permanent = True
if not tag:
return 'error'
tag = tag.strip()
tags = tag.split(',')
for tag in tags:
del_one_tag(tag)
return 'ok'
@views.route('/rename', methods=['POST'])
def rename():
tag = request.form['tag']
newtag = request.form['newtag']
# session.permanent = True
if not tag or not newtag:
return 'error'
tag = tag.strip()
newtag = newtag.strip()
template_root = os.path.abspath(os.path.join(app.root_path, '..'))
logroot = os.path.join(template_root, 'logs')
oldpath = os.path.join(logroot, tag)
newpath = os.path.join(logroot, newtag)
oldckptpath = os.path.join(template_root, 'checkpoints', tag)
newckptpath = os.path.join(template_root, 'checkpoints', newtag)
if os.path.isdir(newpath):
return 'tag exists.'
if not os.path.isdir(oldpath):
return 'old tag not found.'
cmd1 = f'mv {oldpath} {newpath}'
cmd2 = f'mv {oldckptpath} {newckptpath}'
os.system(cmd1)
os.system(cmd2)
return 'ok'
@views.route('/editremark', methods=['POST'])
def editremark():
tag = request.form['tag']
remark = request.form['remark']
# session.permanent = True
if not tag:
return 'error'
if not remark:
remark = ''
template_root = os.path.abspath(os.path.join(app.root_path, '..'))
logroot = os.path.join(template_root, 'logs')
logpath = os.path.join(logroot, tag, 'meta.json')
if not os.path.isfile(logpath):
return 'error'
with open(logpath, 'r') as f:
meta = json.load(f)
meta[0]['remarks'] = remark
with open(logpath, 'w', encoding='utf-8') as f:
json.dump(meta, f, ensure_ascii=False)
return 'ok'
@views.route('/editacc', methods=['POST'])
def editacc():
tag = request.form['tag']
acc = request.form['acc']
# session.permanent = True
if not tag:
return 'error'
if not acc:
acc = '0'
template_root = os.path.abspath(os.path.join(app.root_path, '..'))
logroot = os.path.join(template_root, 'logs')
logpath = os.path.join(logroot, tag, 'meta.json')
if not os.path.isfile(logpath):
return 'error'
with open(logpath, 'r') as f:
meta = json.load(f)
try:
meta[0]['best_acc'] = float(acc)
except:
return 'acc must be float'
with open(logpath, 'w', encoding='utf-8') as f:
json.dump(meta, f, ensure_ascii=False)
return 'ok'
@views.route('/')
@views.route('/index')
def index():
url = request.url_root # http:https://172.20.118.80:8000/
port = 6006
pos = url.rfind(':')
if pos > 6:
tensorboard_url = url[:pos] + f':{port}/'
else:
tensorboard_url = url.rstrip('/') + f':{port}/'
global tensorboard
metas = get_meta() #
tensorboard_not_open = tensorboard is None
template_root = os.path.abspath(os.path.join(app.root_path, '..'))
return render_template('index.html', metas=metas, tensorboard_not_open=tensorboard_not_open, tensorboard_url=tensorboard_url, val=False, path=template_root)
@views.route('/val')
def validation():
url = request.url_root # http:https://172.20.118.80:8000/
port = 6006
pos = url.rfind(':')
if pos > 6:
tensorboard_url = url[:pos] + f':{port}/'
else:
tensorboard_url = url.rstrip('/') + f':{port}/'
global tensorboard
metas = get_meta(dir='results') #
tensorboard_not_open = tensorboard is None
template_root = os.path.abspath(os.path.join(app.root_path, '..'))
return render_template('index.html', metas=metas, tensorboard_not_open=tensorboard_not_open, tensorboard_url=tensorboard_url, val=True, path=template_root)
@views.route('/html/user/static/<path:path>')
def themes_handler(path):
filename = safe_join(app.root_path, 'html', 'user', 'static', path)
if os.path.isfile(filename):
return send_file(filename)
else:
abort(404)