brainframe-sys-tools 0.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,534 @@
1
+ #
2
+ # Copyright (c) 2021 Dilili Labs, Inc. All rights reserved. Contains Dilili Labs Proprietary Information. RESTRICTED
3
+ # COMPUTER SOFTWARE. LIMITED RIGHTS DATA.
4
+ #
5
+
6
+ import json
7
+ from datetime import datetime
8
+ from time import sleep
9
+
10
+ from brainframe.api import BrainFrameAPI, bf_errors
11
+ from brainframe.api.stubs.zone_statuses import ZONE_STATUS_STREAM_TYPE
12
+ from brainframe_sys_tools.brainframe_monitor.curses_utils import plot
13
+ from brainframe_sys_tools.brainframe_monitor.report import Report
14
+ from tabulate import tabulate
15
+ from brainframe_apps.list_stream import stream_status
16
+ from brainframe_apps.fps_report import (
17
+ collect_tstamps,
18
+ format_fresh_tstamp_fps_report,
19
+ calc_fresh_tstamp_fps,
20
+ )
21
+ from queue import Queue
22
+
23
+
24
+ class Benchmarker:
25
+ def __init__(
26
+ self,
27
+ version: str,
28
+ fps_history_file: str,
29
+ report: Report,
30
+ fps_hist_buf_len: int,
31
+ server_url: str,
32
+ refresh_interval: int,
33
+ title_padding: int = 0,
34
+ time_axis_padding: int = 6,
35
+ ):
36
+ """
37
+ :param report: A long existing Report object that carries all the state
38
+ regarding performance.
39
+ :param server_url: BrainFrame server URL.
40
+ :param refresh_interval: How often to refresh the results screen
41
+ :param title_padding:
42
+ """
43
+ self.version = version
44
+ self.report = report
45
+ self.server_url = server_url
46
+ self.refresh_interval = refresh_interval
47
+ self.fps_hist_buf_len = fps_hist_buf_len
48
+ self.title_padding = title_padding
49
+ self.time_axis_padding = time_axis_padding
50
+ self.api: BrainFrameAPI = BrainFrameAPI(server_url=server_url)
51
+
52
+ self.total_streams = 0
53
+ self.total_zs_received = 0
54
+ self.n_zs_buffered = 0
55
+
56
+ # This is set on first connection, and holds a zone_status_iterator
57
+ self.zone_status_connection = None
58
+
59
+ self.num_of_resets = 0
60
+
61
+ self.fps_history_fp = open(fps_history_file, "a")
62
+
63
+ def safe_zs_iterator(self, screen):
64
+ """Catch errors from the zone_status_iterator, reinitialize connection
65
+ only when it has been broken."""
66
+ self.zone_status_connection: ZONE_STATUS_STREAM_TYPE = (
67
+ self.zone_status_connection or self.api.get_zone_status_stream()
68
+ )
69
+
70
+ def display_error(message):
71
+ screen.clear()
72
+ screen.addstr(0, 0, message)
73
+ screen.refresh()
74
+ sleep(0.5)
75
+ self.zone_status_connection = self.api.get_zone_status_stream()
76
+
77
+ while True:
78
+ try:
79
+ for zone_status in self.zone_status_connection:
80
+ yield zone_status
81
+
82
+ except (bf_errors.ServerNotReadyError, json.decoder.JSONDecodeError):
83
+ display_error("Attempting to connect to server...")
84
+
85
+ except (
86
+ bf_errors.LicenseExpiredError,
87
+ bf_errors.LicenseRequiredError,
88
+ bf_errors.LicenseInvalidError,
89
+ ):
90
+ display_error("The BrainFrame server needs a new license!")
91
+
92
+ def __call__(self, screen, time_0):
93
+ tstamp_0 = None
94
+ zs_time_0 = None
95
+ last_start_time = datetime.now()
96
+ self.num_of_resets += 1
97
+ self.fps_history_fp.write(f"\n{last_start_time}: Screen reset\n")
98
+ self.fps_lock_range = False
99
+ self.fps_min = None
100
+ self.fps_max = None
101
+ time_axis_range_hms, time_axis_range_ms = "", ""
102
+
103
+ # Don't wait for user input
104
+ screen.nodelay(True)
105
+ self.plt_width = 60
106
+
107
+ stream_info_list = {}
108
+ fps_hist = Queue(maxsize=self.fps_hist_buf_len)
109
+
110
+ for zone_statuses in self.safe_zs_iterator(screen):
111
+ # Initialize the screen, clock; collect tstamps
112
+ zs_time = datetime.now()
113
+
114
+ pressed_key = screen.getch()
115
+ if pressed_key == ord("q"):
116
+ self.fps_history_fp.close()
117
+ break
118
+
119
+ self.report.times_hist, tstamp_hist_0, is_empty = collect_tstamps(
120
+ self.report.times_hist,
121
+ self.report.times_hist_len,
122
+ zone_statuses,
123
+ zs_time.timestamp(),
124
+ )
125
+ if is_empty:
126
+ continue
127
+
128
+ if zs_time_0 is None:
129
+ zs_time_0 = zs_time
130
+
131
+ if tstamp_0 is None:
132
+ if tstamp_hist_0 is not None:
133
+ tstamp_0 = tstamp_hist_0
134
+ else:
135
+ continue
136
+
137
+ if (zs_time - last_start_time).total_seconds() < self.refresh_interval:
138
+ continue
139
+ last_start_time = zs_time
140
+
141
+ screen.clear()
142
+
143
+ # Output the title line: version, # resets, time_elpase
144
+ time_elapse = zs_time - time_0
145
+ try:
146
+ time_elapse_hms, time_elpase_ms = str(time_elapse).split(".")
147
+ except ValueError:
148
+ time_elapse_hms = str(time_elapse)
149
+ time_elpase_ms = ""
150
+
151
+ row = 0
152
+ screen.addstr(
153
+ row,
154
+ self.title_padding,
155
+ f" BrainFrame Monitor {self.version}{' ' * 11} Reconnect # {self.num_of_resets:03}] {time_elapse_hms}.{time_elpase_ms[:2]}",
156
+ )
157
+ row += 1
158
+
159
+ # Create/output the overall stream throughput report table
160
+ stream_info_list = self.update_stream_info(stream_info_list)
161
+
162
+ (
163
+ throughput_fps,
164
+ avg_fps,
165
+ max_fps_t,
166
+ min_fps_t,
167
+ stream_fps_drift_dsync,
168
+ ) = calc_fresh_tstamp_fps(
169
+ self.report.times_hist,
170
+ tstamp_0,
171
+ zs_time_0,
172
+ zone_statuses,
173
+ zs_time.timestamp(),
174
+ )
175
+
176
+ (
177
+ stream_fps_summary_header,
178
+ stream_fps_summary,
179
+ throughput_fps_str,
180
+ ) = format_fresh_tstamp_fps_report(
181
+ throughput_fps, avg_fps, max_fps_t, min_fps_t
182
+ )
183
+
184
+ self.fps_history_fp.write(
185
+ f"{time_elapse_hms}.{time_elpase_ms[:2]} {throughput_fps_str}\n"
186
+ )
187
+ self.fps_history_fp.flush()
188
+
189
+ table_str = tabulate(
190
+ [stream_fps_summary],
191
+ tablefmt="fancy_grid",
192
+ headers=stream_fps_summary_header,
193
+ )
194
+
195
+ screen.addstr(row, 0, table_str)
196
+ row += 5
197
+
198
+ # Output stream fps list
199
+ stream_fps_list = self.get_stream_fps_list(
200
+ stream_info_list, stream_fps_drift_dsync
201
+ )
202
+ table_str = tabulate(
203
+ stream_fps_list,
204
+ headers=[
205
+ " A/K",
206
+ "sID",
207
+ "Stream url",
208
+ "FPS",
209
+ "[ Buf, Age,Dsync,Drift]",
210
+ ],
211
+ showindex="never",
212
+ )
213
+
214
+ screen.addstr(row, 0, table_str)
215
+ row += len(stream_fps_list) + 2
216
+
217
+ # Output the plot title line: number of samples, and total measures
218
+ self.total_zs_received += 1
219
+ if self.total_zs_received < self.fps_hist_buf_len:
220
+ zs_time_elapse = zs_time - zs_time_0
221
+ try:
222
+ time_axis_range_hms, time_axis_range_ms = str(zs_time_elapse).split(
223
+ "."
224
+ )
225
+ except ValueError:
226
+ time_axis_range_hms = str(zs_time_elapse)
227
+ time_axis_range_ms = ""
228
+
229
+ if self.total_zs_received < self.report.times_hist_len:
230
+ self.n_zs_buffered = self.total_zs_received
231
+ else:
232
+ self.n_zs_buffered = self.report.times_hist_len
233
+
234
+ if self.total_zs_received >= self.fps_hist_buf_len + self.n_zs_buffered:
235
+ # Change this to True to enable fps lock
236
+ self.fps_lock_range = False
237
+ fps_range_str = f" FPS" # axis locked{' ' * 9}"
238
+ else:
239
+ self.fps_lock_range = False
240
+ fps_range_str = (
241
+ f" FPS" # axis locking.{'.' * (self.n_zs_buffered % 3):6s} "
242
+ )
243
+
244
+ scr_rows, scr_cols = screen.getmaxyx()
245
+ plt_height_limit = scr_rows - row - 7
246
+ self.fps_min, self.fps_max, cfg = self.save_fps_throughput(
247
+ self.fps_hist_buf_len,
248
+ plt_height_limit,
249
+ self.plt_width,
250
+ fps_hist,
251
+ throughput_fps,
252
+ self.fps_lock_range,
253
+ self.fps_min,
254
+ self.fps_max,
255
+ )
256
+
257
+ row += 1
258
+ screen.addstr(
259
+ row,
260
+ self.title_padding,
261
+ f"FPS/max/min: {throughput_fps_str}/{self.fps_max:.2f}/{self.fps_min:.2f}, total {self.total_zs_received} zone statuses received, {self.n_zs_buffered:>3} in buffer",
262
+ )
263
+ row += 1
264
+
265
+ # Plot fps throughput graph
266
+ plot_txt, plot_n_rows, debug_print = plot(
267
+ fps_hist, self.fps_min, self.fps_max, cfg=cfg
268
+ )
269
+
270
+ screen.addstr(row, 0, plot_txt)
271
+ row += plot_n_rows + 1
272
+
273
+ # Output plot time axis information lines
274
+ t_step = int(10 * self.fps_hist_buf_len / self.plt_width)
275
+ t_max = int(self.fps_hist_buf_len / t_step)
276
+ t_label = "0"
277
+ for t in range(t_max):
278
+ t_label += f"{str((t + 1) * t_step):>10}"
279
+ screen.addstr(row, self.time_axis_padding, t_label)
280
+ row += 1
281
+
282
+ screen.addstr(
283
+ row,
284
+ self.title_padding,
285
+ f"{' ' * 9}Refresh interval: {self.refresh_interval} seconds,"
286
+ f" Time axis range: {time_axis_range_hms}.{time_axis_range_ms[:2]}",
287
+ )
288
+ row += 2
289
+
290
+ # Output press key prompt and debug information
291
+ screen.addstr(
292
+ row,
293
+ 5,
294
+ f"Total {self.total_streams} streams measured. Press q to quit {debug_print}",
295
+ )
296
+
297
+ screen.refresh()
298
+
299
+ def get_stream_info_list(self):
300
+
301
+ stream_info_list = {}
302
+ streams = self.api.get_stream_configurations()
303
+ for stream in streams:
304
+ (
305
+ analyze_status,
306
+ keyframes_only_status,
307
+ stream_url,
308
+ ) = stream_status(self.api, stream, stream.id)
309
+ stream_info_item = {
310
+ "analyze_status": analyze_status,
311
+ "keyframes_only_status": keyframes_only_status,
312
+ "stream_url": stream_url,
313
+ }
314
+ stream_info_list[stream.id] = stream_info_item
315
+ self.fps_history_fp.write(f"{stream_info_item}\n")
316
+
317
+ self.fps_history_fp.write(f"TimeElapse FPS\n")
318
+ return stream_info_list
319
+
320
+ def update_stream_info(self, stream_info_list):
321
+ times_hist = self.report.times_hist
322
+ for stream_id, stream_times in times_hist.items():
323
+
324
+ # let's refresh the whole list
325
+ # - When a new stream is observed
326
+ # - When a stream is added or deleted
327
+ if stream_id not in stream_info_list or len(times_hist) != len(
328
+ stream_info_list
329
+ ):
330
+ self.total_streams += 1
331
+ try:
332
+ stream_info_list = self.get_stream_info_list()
333
+ except:
334
+ pass
335
+
336
+ # In case a stream is deleted
337
+ break
338
+ return stream_info_list
339
+
340
+ @staticmethod
341
+ def get_stream_fps_list(stream_info_list, stream_fps_drift_dsync):
342
+ stream_fps_list = []
343
+ stream_info_list_index = 1
344
+ for stream_id in sorted(stream_info_list):
345
+ stream_info_item = stream_info_list[stream_id]
346
+ fps_str = ""
347
+ buf_str = " "
348
+ age_str = " "
349
+ dsync_str = " "
350
+ drift_str = " "
351
+ if stream_id in stream_fps_drift_dsync:
352
+ fps_drift_dsync = stream_fps_drift_dsync[stream_id]
353
+ if "fps" in fps_drift_dsync:
354
+ fps = fps_drift_dsync["fps"]
355
+ if fps != 0:
356
+ fps_str = f"{fps_drift_dsync['fps']:>5.1f}"
357
+
358
+ if (
359
+ "drift" in fps_drift_dsync
360
+ and fps_drift_dsync["drift"] is not None
361
+ ):
362
+ drift_str = f"{fps_drift_dsync['drift']: >5.2f}"
363
+
364
+ if (
365
+ "dsync" in fps_drift_dsync
366
+ and fps_drift_dsync["dsync"] is not None
367
+ ):
368
+ dsync_str = f"{fps_drift_dsync['dsync']: >5.2f}"
369
+
370
+ if "age" in fps_drift_dsync and fps_drift_dsync["age"] is not None:
371
+ age_str = f"{fps_drift_dsync['age']: >5.2f}"
372
+
373
+ if "buf" in fps_drift_dsync and fps_drift_dsync["buf"] is not None:
374
+ buf_str = f"{fps_drift_dsync['buf']: >5.2f}"
375
+
376
+ stream_fps_list.append(
377
+ [
378
+ f"{stream_info_list_index}: {stream_info_item['analyze_status']}/{stream_info_item['keyframes_only_status']}",
379
+ f"{stream_id}",
380
+ f"{str(stream_info_item['stream_url'])[-25:]:.>25}",
381
+ fps_str,
382
+ f"[{buf_str},{age_str},{dsync_str},{drift_str}]",
383
+ ]
384
+ )
385
+ stream_info_list_index = stream_info_list_index + 1
386
+
387
+ return stream_fps_list
388
+
389
+ def save_fps_throughput(
390
+ self,
391
+ fps_hist_buf_len,
392
+ plt_height_limit,
393
+ plt_width,
394
+ fps_hist,
395
+ throughput,
396
+ fps_lock_range,
397
+ curr_fps_min,
398
+ curr_fps_max,
399
+ ):
400
+ cfg = {
401
+ "fps_hist_buf_len": fps_hist_buf_len,
402
+ "plt_height_limit": plt_height_limit,
403
+ "plt_width": plt_width,
404
+ "col_offset": 2,
405
+ }
406
+
407
+ if fps_hist.qsize() >= fps_hist_buf_len:
408
+ fps_hist.get()
409
+
410
+ if throughput is not None:
411
+ fps_hist.put(int(throughput))
412
+
413
+ if fps_hist.qsize() > 0:
414
+ if fps_lock_range is False or curr_fps_min is None:
415
+ fps_min = float(min(list(fps_hist.queue)))
416
+ else:
417
+ fps_min = min(float(min(list(fps_hist.queue))), curr_fps_min)
418
+
419
+ if fps_lock_range is False or curr_fps_max is None:
420
+ fps_max = float(max(list(fps_hist.queue)))
421
+ else:
422
+ fps_max = max(float(max(list(fps_hist.queue))), curr_fps_max)
423
+ else:
424
+ fps_min = 0
425
+ fps_max = 0
426
+
427
+ return fps_min, fps_max, cfg
428
+
429
+
430
+ def test_plot():
431
+ from random import random
432
+
433
+ benchmarker = Benchmarker(
434
+ version="v0.0",
435
+ fps_history_file="test_plot.txt",
436
+ report=None,
437
+ fps_hist_buf_len=100,
438
+ server_url="",
439
+ refresh_interval=0,
440
+ )
441
+
442
+ fps_data = []
443
+ n_tests = 55
444
+ fps_sample_data_max = 30
445
+ for i in range(n_tests):
446
+ # test fixed pattern or random pattern?
447
+ value = i % fps_sample_data_max
448
+ # value = float(random() * 29)
449
+ fps_data.append(value)
450
+
451
+ fps_data = [3, 3, 3, 7, 6, 6, 9, 11, 8, 1, 1, 2, 902]
452
+ # fps_data = [122]
453
+ """
454
+ fps_data = [
455
+ 224,
456
+ 104,
457
+ 1,
458
+ 2,
459
+ 3,
460
+ 70,
461
+ 60,
462
+ 56,
463
+ 40,
464
+ 25,
465
+ 14,
466
+ 14,
467
+ 13,
468
+ 12,
469
+ 11,
470
+ 10,
471
+ 10,
472
+ 10,
473
+ 9,
474
+ 9,
475
+ 9,
476
+ 9,
477
+ 8,
478
+ 8,
479
+ 8,
480
+ 8,
481
+ 8,
482
+ 8,
483
+ 8,
484
+ 8,
485
+ 7,
486
+ 7,
487
+ 7,
488
+ 431,
489
+ 136,
490
+ 98,
491
+ 61,
492
+ 11,
493
+ 9,
494
+ 8,
495
+ 8,
496
+ 6,
497
+ 6,
498
+ 6,
499
+ 4,
500
+ 4,
501
+ 4,
502
+ 4,
503
+ 4,
504
+ 4,
505
+ 4,
506
+ 4,
507
+ 4,
508
+ 3,
509
+ 1357,
510
+ 147,
511
+ 80,
512
+ 57,
513
+ 40,
514
+ 39,
515
+ ]
516
+ """
517
+ plt_height_limit = 20
518
+ plt_width = 60
519
+
520
+ fps_hist_buf_len = 100
521
+ fps_hist = Queue(maxsize=fps_hist_buf_len)
522
+ for i, value in enumerate(fps_data):
523
+ throughput = value
524
+ curr_fps_min, curr_fps_max, cfg = benchmarker.save_fps_throughput(
525
+ fps_hist_buf_len, plt_height_limit, plt_width, fps_hist, throughput, False
526
+ )
527
+ plot_txt, plot_n_rows, debug_print = plot(
528
+ fps_hist, curr_fps_min, curr_fps_max, cfg
529
+ )
530
+ print(f"{plot_txt}\nIndex: {i}, fps: {value}\n{debug_print}")
531
+
532
+
533
+ if __name__ == "__main__":
534
+ test_plot()
@@ -0,0 +1,105 @@
1
+ #
2
+ # Copyright (c) 2021 Dilili Labs, Inc. All rights reserved. Contains Dilili Labs Proprietary Information. RESTRICTED
3
+ # COMPUTER SOFTWARE. LIMITED RIGHTS DATA.
4
+ #
5
+
6
+ import curses
7
+ from argparse import ArgumentParser
8
+
9
+ from brainframe_sys_tools.brainframe_monitor.benchmarker import Benchmarker
10
+ from brainframe_sys_tools.brainframe_monitor.fake_screen import FakeScreen
11
+ from brainframe_sys_tools.brainframe_monitor.report import Report
12
+ from datetime import datetime
13
+ from brainframe_sys_tools.command_utils import command, subcommand_parse_args, by_name
14
+
15
+
16
+ @command("fps_monitor")
17
+ def fps_monitor():
18
+ version = "v2.0"
19
+ args = _parse_args(version)
20
+ no_screen = args.no_screen
21
+
22
+ report = Report(
23
+ times_hist_len=args.times_hist_len,
24
+ )
25
+ fps_hist_buf_len = args.duration / args.refresh_interval
26
+ benchmarker = Benchmarker(
27
+ version=version,
28
+ fps_history_file=args.out,
29
+ report=report,
30
+ fps_hist_buf_len=fps_hist_buf_len,
31
+ server_url=args.server_url,
32
+ refresh_interval=args.refresh_interval,
33
+ )
34
+ time_0 = datetime.now()
35
+ while True:
36
+ try:
37
+ if no_screen is None:
38
+ curses.wrapper(benchmarker, time_0)
39
+ else:
40
+ screen = FakeScreen
41
+ benchmarker.__call__(screen, time_0)
42
+ break
43
+ except curses.error:
44
+ # This occurs when the terminal is too small
45
+ pass
46
+
47
+
48
+ def _parse_args(version):
49
+ parser = ArgumentParser(description=f"BrainFrame FPS Monitor {version}")
50
+ parser.add_argument(
51
+ "--refresh-interval",
52
+ default=0.5,
53
+ type=float,
54
+ help=(
55
+ "An interval to refresh results at. Values that are too low might effect "
56
+ "result accuracy, default %(default)s"
57
+ ),
58
+ )
59
+ parser.add_argument(
60
+ "--times-hist-len",
61
+ default=100,
62
+ type=int,
63
+ help="The number of zone status samples to wait on before displaying results, "
64
+ "default %(default)s",
65
+ )
66
+ parser.add_argument(
67
+ "--duration",
68
+ default=30,
69
+ type=int,
70
+ help="How many seconds long the stream responses are plotting, "
71
+ "default %(default)s",
72
+ )
73
+ parser.add_argument(
74
+ "--server-url",
75
+ default="http://localhost",
76
+ help="The url to the server, probably in the format of "
77
+ "http://IP_ADDRESS:PORT, default %(default)s",
78
+ )
79
+ parser.add_argument(
80
+ "--out",
81
+ default="brainframe_monitor.fps_history",
82
+ help="FPS throughput history will be saved in an output file.",
83
+ )
84
+ parser.add_argument(
85
+ "--no-screen",
86
+ dest="no_screen",
87
+ action="store_false",
88
+ default=None,
89
+ help="Use fake_screen to print instead of Python curses screen util",
90
+ )
91
+ parser.add_argument(
92
+ "--version", action="store_true", help="Returns the version of the script"
93
+ )
94
+
95
+ args = subcommand_parse_args(parser)
96
+
97
+ if args.version:
98
+ print(version)
99
+ exit(0)
100
+
101
+ return args
102
+
103
+
104
+ if __name__ == "__main__":
105
+ by_name["fps_monitor"]()