-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathlivedemo.py
196 lines (143 loc) · 4.46 KB
/
livedemo.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
import re
import json
import os
import time
import numpy
import serial
import scipy.signal
import matplotlib
from matplotlib import pyplot as plt
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
classes = {
'car_horn': 1,
'dog_bark': 3,
'children_playing': 2,
'engine_idling': 5,
'street_music': 9,
'drilling': 4,
'air_conditioner': 0,
'gun_shot': 6,
'siren': 8,
'jackhammer': 7,
'unknown': 10,
'quiet': 11,
}
classnames = [ ni[0] for ni in sorted(classes.items(), key=lambda kv: kv[1]) ]
def parse_input(line):
line = line.strip()
prefix = 'preds:'
if line.startswith(prefix):
value_str = line.lstrip(prefix).rstrip(',')
values = [ float(s) for s in value_str.split(',') ]
return values
else:
return None
example_input = """
Classifier: 44 ms
preds:0.099867,0.043521,0.233744,0.162579,0.068373,0.049388,0.024437,0.042881,0.046287,0.228922,
MelColumn: 62 ms
LogMelSpec: 3 ms
Classifier: 43 ms
Sending: ASC=2
preds:0.056955,0.022613,0.327033,0.140140,0.028910,0.026387,0.015121,0.012570,0.021695,0.348576,
MelColumn: 31 ms
LogMelSpec: 3 ms
Classifier: 43 ms
"""
def test_parse_preds():
inp = example_input
parsed = [ parse_input(l) for l in inp.split('\n') ]
valid = [ v for v in parsed if v is not None ]
assert len(parsed) == 12, len(parsed) # lines
assert len(valid) == 2 # predictions
assert len(valid[1]) == 10 # classes
assert len(valid[0]) == 10 # classes
assert valid[0][0] == 0.099867, valid[0]
assert valid[1][2] == 0.327033, valid[1]
def create_interactive():
win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.set_default_size(400, 300)
win.set_title("On-sensor Audio Classification")
fig, (ax, text_ax) = plt.subplots(1, 2)
sw = Gtk.ScrolledWindow()
win.add(sw)
# A scrolled window border goes outside the scrollbars and viewport
sw.set_border_width(10)
canvas = FigureCanvas(fig) # a Gtk.DrawingArea
canvas.set_size_request(200, 400)
sw.add_with_viewport(canvas)
prediction_threshold = 0.35
# Plots
predictions = numpy.zeros(11)
tt = numpy.arange(len(predictions))
rects = ax.barh(tt, predictions, align='center', alpha=0.5)
ax.set_yticks(tt)
ax.set_yticklabels(classnames)
ax.set_xlim(0, 1)
ax.axvline(prediction_threshold)
ax.yaxis.set_ticks_position('right')
# Text
text_ax.axes.get_xaxis().set_visible(False)
text_ax.axes.get_yaxis().set_visible(False)
text = text_ax.text(0.5, 0.2, "Unknown",
horizontalalignment='center',
verticalalignment='center',
fontsize=32,
)
def emwa(new, prev, alpha):
return alpha * new + (1 - alpha) * prev
prev = predictions
alpha = 0.2 # smoothing coefficient
window = numpy.zeros(shape=(4, 11))
from scipy.ndimage.interpolation import shift
def update_plot(predictions):
if len(predictions) < 10:
return
# add unknown class
predictions = numpy.concatenate([predictions, [0.0]])
window[:, :] = numpy.roll(window, 1, axis=0)
window[0, :] = predictions
predictions = numpy.mean(window, axis=0)
best_p = numpy.max(predictions)
best_c = numpy.argmax(predictions)
if best_p <= prediction_threshold:
best_c = 10
best_p = 0.0
for rect, h in zip(rects, predictions):
rect.set_width(h)
name = classnames[best_c]
text.set_text(name)
fig.tight_layout()
fig.canvas.draw()
return win, update_plot
def fetch_predictions(ser):
raw = ser.readline()
line = raw.decode('utf-8')
predictions = parse_input(line)
return predictions
def main():
test_parse_preds()
device = '/dev/ttyACM1'
baudrate = 115200
window, plot = create_interactive()
window.show_all()
def update(ser):
try:
preds = fetch_predictions(ser)
except Exception as e:
print('error', e)
return True
if preds is not None:
plot(preds)
return True
with serial.Serial(device, baudrate, timeout=0.1) as ser:
# avoid reading stale data
thrash = ser.read(10000)
GLib.timeout_add(200.0, update, ser)
Gtk.main() # WARN: blocking
if __name__ == '__main__':
main()