-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
272 lines (229 loc) · 6.64 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<script src="fingerclicknn.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<style>
body {
width: 1036px;
}
</style>
</head>
<body>
<button onclick="start()">Start using mic</button>
<script type="text/javascript">
let model;
(async () => {
try {
model = await tf.loadLayersModel('localstorage://myModel');
} catch(e) {
model = tf.sequential();
model.add(tf.layers.conv1d({
inputShape: [256, 1],
kernelSize: 3,
filters: 32,
activation: 'relu',
}));
model.add(tf.layers.maxPooling1d({
poolSize: 2,
strides: 2,
}));
model.add(tf.layers.flatten());
model.add(tf.layers.dense({
units: 1,
activation: 'sigmoid'
}));
}
model.compile({
optimizer: tf.train.adam(0.001),
loss: 'binaryCrossentropy',
metrics: ['accuracy']
});
})();
function hslToRgb(h, s, l) {
let r, g, b;
if (s == 0) {
r = g = b = l;
} else {
function hue2rgb(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1/6) return p + (q - p) * 6 * t;
if (t < 1/2) return q;
if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
let q = l < 0.5 ? l * (1 + s) : l + s - l * s;
let p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return { r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255) };
}
function drawRectangleHSL(imgData, x, y, width, height, h, s, l) {
let endX = x + width,
endY = y + height,
{ r, g, b } = hslToRgb(h, s, l),
data = imgData.data;
for (let iy = y; iy < endY; iy++) {
for (let ix = x; ix < endX; ix++) {
let pixelIndex = (iy * imgData.width + ix) * 4;
data[pixelIndex + 0] = r;
data[pixelIndex + 1] = g;
data[pixelIndex + 2] = b;
data[pixelIndex + 3] = 255;
}
}
}
async function createCanvas(stream) {
let context = new AudioContext();
document.body.innerHTML = '<span>Use LMB to mark spectrogram column as a positive sample, and this checkbox when you need to train negative samples (do not produce target sounds while it is checked):</span><input type="checkbox" /><br /><canvas height="512" width="1024"></canvas><br /><button onclick="copyWeightsToClipboard()">Copy weights to clipboard</button><button onclick="loadFingerClickNN()">Load Finger Click NN</button><button onclick="clearSavedNN()">Clear saved data</button><br /><a href="https://github.com/alexanderbrodko/fingerclick">GitHub</a>';
let can = document.querySelector('canvas'),
ctx = can.getContext('2d'),
imgData = ctx.createImageData(1024, 512),
negativeTraining = document.querySelector('input'),
button = document.querySelector('button');
negativeTraining.onchange = () => {
if (!negativeTraining.checked) {
let trainData = [];
let trainLabels = [];
for (let item of data) {
if (!item.negativeTrained) break;
trainData.push(item.trainData);
trainLabels.push(0);
}
trainData = tf.concat(trainData, 0);
trainLabels = tf.tensor1d(trainLabels);
model.fit(trainData, trainLabels, {
epochs: 50,
shuffle: true,
validationSplit: 0.1
});
}
};
window.copyWeightsToClipboard = function () {
let arr = [];
for (let name in window.FingerClickNN) {
arr.push('"' + name + '": "' + btoa(localStorage.getItem('tensorflowjs_models/myModel/' + name)) + '"');
}
let text = '{' + arr.join(',') + '}';
let textarea = document.createElement("textarea");
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
};
window.loadFingerClickNN = function () {
for (let name in window.FingerClickNN) {
localStorage.setItem('tensorflowjs_models/myModel/' + name, atob(window.FingerClickNN[name]));
}
location.reload();
};
window.clearSavedNN = function () {
localStorage.clear();
location.reload();
};
let input = context.createMediaStreamSource(stream);
let analyser = context.createAnalyser();
analyser.fftSize = 512;
input.connect(analyser);
let col = -1,
XSCALE = 8,
YSCALE = 2;
can.onmousemove = e => {
col = (e.offsetX / XSCALE) | 0;
let row = ((can.height - e.offsetY) / YSCALE) | 0;
let str = 'Col: ' + col + '\nFreq: ' + Math.floor(row / analyser.fftSize * context.sampleRate);
if (data[col]) {
str += '\nVal: ' + data[col].sample[row];
}
can.title = str;
};
let data = [];
can.onclick = e => {
col = (e.offsetX / XSCALE) | 0;
if (data[col]) {
let trainLabels = tf.tensor1d([1]);
model.fit(data[col].trainData, trainLabels, {
epochs: 1,
validationSplit: 1
});
data[col].positiveTrained = true;
model.save('localstorage://myModel');
}
};
let isUpdating = true;
can.addEventListener('mouseover', () => isUpdating = false);
can.addEventListener('mouseout', () => {
isUpdating = true;
col = -1;
});
(function update() {
if (isUpdating) {
let freqByteData = new Uint8Array(512);
analyser.getByteFrequencyData(freqByteData);
let sample = [];
for (let i = 0; i < 256; i++) {
sample[i] = freqByteData[i] / 255;
}
let trainData = tf.tensor3d(sample, [1, 256, 1]);
let predictionGood = model.predict(trainData).dataSync()[0] > 0.9;
data.unshift({ sample, trainData, predictionGood, negativeTrained: negativeTraining.checked });
let maxSamples = can.width / XSCALE;
if (data.length > maxSamples) {
data.length = maxSamples;
}
}
for (let x = 0; x < data.length; x++) {
let { sample, gradient, predictionGood, negativeTrained, positiveTrained } = data[x];
for (let y = 0; y < sample.length; y++) {
let value = sample[y],
h = (250 - (value * 360) | 0) / 360,
s = 1,
l = 0.5;
if (x === col) {
if (value) {
l = 0.8;
} else {
l = 1;
}
} else if (negativeTrained) {
if (value) {
l = value;
} else {
h = 0;
s = 0.5;
l = 0.3;
}
} else if (positiveTrained) {
if (value) {
l = value;
} else {
h = 120 / 360;
s = 0.5;
l = 0.5;
}
} else if (predictionGood) {
l = 0.6;
} else {
if (value) {
l = 0.5;
} else {
l = 0;
}
}
drawRectangleHSL(imgData, x * XSCALE, can.height - y * YSCALE, XSCALE, YSCALE, h, s, l);
}
}
ctx.putImageData(imgData, 0, 0);
setTimeout(update, 10);
})();
}
function start() {
navigator.getUserMedia({ audio: true }, createCanvas, e => alert(e));
}
</script>
</body>
</html>