-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNNsnake.html
More file actions
733 lines (642 loc) · 31.1 KB
/
NNsnake.html
File metadata and controls
733 lines (642 loc) · 31.1 KB
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
<!DOCTYPE html>
<html lang="uk">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voice CNN Snake v3 (Mel + Latent)</title>
<script src="https://cdn.plot.ly/plotly-2.27.0.min.js"></script>
<style>
:root {
--bg: #0f172a; --panel: #1e293b; --text: #f1f5f9;
--accent: #3b82f6; --success: #22c55e; --danger: #ef4444; --warn: #f59e0b;
}
body { font-family: 'Segoe UI', sans-serif; background: var(--bg); color: var(--text); margin: 0; display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
header { padding: 10px 20px; background: var(--panel); border-bottom: 1px solid #334155; display: flex; justify-content: space-between; align-items: center; }
h1 { margin: 0; font-size: 1.2rem; color: var(--accent); }
.workspace { display: grid; grid-template-columns: 340px 1fr 300px; gap: 10px; padding: 10px; height: calc(100vh - 60px); }
.panel { background: var(--panel); border-radius: 8px; padding: 15px; overflow-y: auto; border: 1px solid #334155; display: flex; flex-direction: column; gap: 10px; }
.panel h3 { margin-top: 0; border-bottom: 1px solid #475569; padding-bottom: 5px; font-size: 1rem; color: #94a3b8; }
button { padding: 10px; border-radius: 6px; border: none; cursor: pointer; font-weight: bold; background: #334155; color: white; transition: 0.2s; }
button:hover { background: #475569; }
button:disabled { opacity: 0.5; cursor: not-allowed; }
.btn-rec { display: flex; align-items: center; justify-content: space-between; margin-bottom: 5px; border: 1px solid #475569; }
.btn-rec.recording { background: #fee2e2; color: #b91c1c; border-color: #ef4444; animation: pulse 1s infinite; }
.count-badge { background: #0f172a; padding: 2px 6px; border-radius: 4px; font-size: 0.8em; }
.btn-primary { background: var(--accent); } .btn-primary:hover { background: #2563eb; }
.btn-success { background: var(--success); color: #000; } .btn-success:hover { background: #16a34a; }
canvas { background: black; border-radius: 4px; width: 100%; }
#spectrogramCanvas { height: 120px; image-rendering: pixelated; }
#snakeCanvas { flex: 1; border: 2px solid #334155; }
.pred-row { display: flex; align-items: center; gap: 10px; margin-bottom: 5px; font-size: 0.9em; }
.bar-bg { flex: 1; height: 8px; background: #334155; border-radius: 4px; overflow: hidden; }
.bar-fill { height: 100%; background: var(--accent); width: 0%; transition: width 0.1s; }
.pred-row.active .bar-fill { background: var(--success); }
.pred-row.active { font-weight: bold; color: var(--success); }
.pred-row.disabled { opacity: 0.3; }
input[type=range] { width: 100%; accent-color: var(--accent); }
@keyframes pulse { 0% { opacity: 1; } 50% { opacity: 0.6; } 100% { opacity: 1; } }
.io-group { display: flex; gap: 5px; }
.io-group button { flex: 1; font-size: 0.8em; }
</style>
</head>
<body>
<header>
<h1>🧠 Voice Mel-CNN (2-Neuron Bottleneck)</h1>
<div style="font-size: 0.8rem; color: #94a3b8;">Mel-Spectrogram & Latent Space</div>
</header>
<div class="workspace">
<div class="panel">
<h3>1. Збір Mel-даних</h3>
<p style="font-size:0.8rem; color:#cbd5e1;">Говоріть чітко. 10+ прикладів.</p>
<button id="btnRec0" class="btn-rec" onmousedown="startRec(0)" onmouseup="stopRec()" ontouchstart="startRec(0)" ontouchend="stopRec()">
<span>🛑 "Стоп"</span> <span id="cnt0" class="count-badge">0</span>
</button>
<button id="btnRec1" class="btn-rec" onmousedown="startRec(1)" onmouseup="stopRec()" ontouchstart="startRec(1)" ontouchend="stopRec()">
<span>⬆️ "Вперед"</span> <span id="cnt1" class="count-badge">0</span>
</button>
<button id="btnRec2" class="btn-rec" onmousedown="startRec(2)" onmouseup="stopRec()" ontouchstart="startRec(2)" ontouchend="stopRec()">
<span>➡️ "Праворуч"</span> <span id="cnt2" class="count-badge">0</span>
</button>
<button id="btnRec3" class="btn-rec" onmousedown="startRec(3)" onmouseup="stopRec()" ontouchstart="startRec(3)" ontouchend="stopRec()">
<span>⬅️ "Ліворуч"</span> <span id="cnt3" class="count-badge">0</span>
</button>
<div><canvas id="spectrogramCanvas" width="32" height="32"></canvas></div>
<h3>2. Навчання</h3>
<button id="btnTrain" class="btn-primary" onclick="trainNetwork()">🚀 Навчити (Bottleneck)</button>
<div style="font-size: 0.8rem; color: #94a3b8; margin-top:5px;">Втрати (Loss):</div>
<div id="loss-plot" style="height: 80px;"></div>
<div style="font-size: 0.8rem; color: #94a3b8; margin-top:5px;">Латентний простір (2 нейрони):</div>
<div id="latent-plot" style="height: 200px; background: #0f172a; border-radius: 4px; border:1px solid #334155;"></div>
<div class="io-group" style="margin-top:10px;">
<button onclick="saveNetwork()" class="btn-success">💾 Save</button>
<button onclick="document.getElementById('fileInput').click()" style="background:#475569;">📂 Load</button>
<input type="file" id="fileInput" style="display:none" onchange="loadNetwork(this)">
</div>
</div>
<div class="panel" style="padding: 0; overflow: hidden; position: relative;">
<canvas id="snakeCanvas"></canvas>
<div id="gameOverlay" style="position: absolute; top:50%; left:50%; transform:translate(-50%, -50%); text-align: center; background: rgba(0,0,0,0.8); padding: 20px; border-radius: 10px; pointer-events: none;">
<h2 style="color: var(--accent);">Voice Snake</h2>
<p>Скажіть "Вперед"!</p>
</div>
<div style="position: absolute; top: 10px; right: 10px; font-size: 1.5rem; font-weight: bold; color: rgba(255,255,255,0.5);">Score: <span id="scoreVal" style="color:white">0</span></div>
<div style="position: absolute; bottom: 10px; left: 10px; font-size: 0.9rem; color: #94a3b8;">Тертя: <span id="momentumVal" style="color:white">0%</span></div>
</div>
<div class="panel">
<h3>🔍 Параметри</h3>
<button id="btnListen" class="btn-success" onclick="toggleListening()">🎙️ Старт мікрофону</button>
<div style="margin: 15px 0; border-top:1px solid #334155; padding-top:10px;">
<label style="font-size:0.9rem; display:flex; justify-content:space-between;">
<span>Noise Gate</span> <span id="gateVal">10%</span>
</label>
<input type="range" id="noiseGate" min="0" max="100" value="10" oninput="document.getElementById('gateVal').innerText = this.value + '%'">
<div style="height: 5px; background: #334155; border-radius: 2px; margin-top: 5px; overflow: hidden;">
<div id="volBar" style="height: 100%; width: 0%; background: #ef4444; transition: width 0.1s;"></div>
</div>
</div>
<h3>Передбачення</h3>
<div id="predictions"></div>
<div style="margin-top: auto; border-top: 1px solid #334155; padding-top: 10px;">
<div style="font-size: 0.8rem; color: #94a3b8;">Cmd: <span id="lastCmd" style="color: var(--accent); font-weight: bold;">-</span></div>
</div>
</div>
</div>
<script>
/**
* === ЧАСТИНА 1: CNN з 2-Neuron Bottleneck ===
*/
class Layer {
constructor() { this.input = null; this.output = null; }
forward(input) { return input; }
backward(grad) { return grad; }
}
class Conv2D extends Layer {
constructor(inChannels, outChannels, kernelSize=3) {
super();
this.inChannels = inChannels; this.outChannels = outChannels; this.k = kernelSize;
const scale = Math.sqrt(2.0 / (inChannels * kernelSize * kernelSize));
this.filters = new Float32Array(outChannels * inChannels * kernelSize * kernelSize).map(() => (Math.random() - 0.5) * 2 * scale);
this.biases = new Float32Array(outChannels).fill(0);
this.gradFilters = new Float32Array(this.filters.length); this.gradBiases = new Float32Array(this.biases.length);
}
forward(input) {
this.input = input; const { w, h, d } = input;
const outW = (w - this.k) + 1; const outH = (h - this.k) + 1;
this.output = { w: outW, h: outH, d: this.outChannels, data: new Float32Array(outW * outH * this.outChannels) };
for (let oc = 0; oc < this.outChannels; oc++) {
for (let y = 0; y < outH; y++) {
for (let x = 0; x < outW; x++) {
let sum = this.biases[oc];
for (let ic = 0; ic < d; ic++) {
for (let ky = 0; ky < this.k; ky++) {
for (let kx = 0; kx < this.k; kx++) {
sum += input.data[(ic * h + (y + ky)) * w + (x + kx)] * this.filters[((oc * d + ic) * this.k + ky) * this.k + kx];
}
}
}
this.output.data[(oc * outH + y) * outW + x] = sum > 0 ? sum : 0; // ReLU
}
}
}
return this.output;
}
backward(gradOutput) {
const { w: inW, h: inH, d: inD } = this.input;
const { w: outW, h: outH, d: outD } = this.output;
const gradInput = new Float32Array(inD * inH * inW).fill(0);
this.gradFilters.fill(0); this.gradBiases.fill(0);
for (let oc = 0; oc < outD; oc++) {
for (let y = 0; y < outH; y++) {
for (let x = 0; x < outW; x++) {
const idx = (oc * outH + y) * outW + x;
let chain = gradOutput.data[idx];
if (this.output.data[idx] <= 0) chain = 0;
this.gradBiases[oc] += chain;
for (let ic = 0; ic < inD; ic++) {
for (let ky = 0; ky < this.k; ky++) {
for (let kx = 0; kx < this.k; kx++) {
const inIdx = (ic * inH + (y + ky)) * inW + (x + kx);
const fIdx = ((oc * inD + ic) * this.k + ky) * this.k + kx;
this.gradFilters[fIdx] += this.input.data[inIdx] * chain;
gradInput[inIdx] += this.filters[fIdx] * chain;
}
}
}
}
}
}
return { w: inW, h: inH, d: inD, data: gradInput };
}
}
class MaxPool2x2 extends Layer {
forward(input) {
this.input = input; const { w, h, d } = input;
const outW = Math.floor(w / 2); const outH = Math.floor(h / 2);
this.output = { w: outW, h: outH, d: d, data: new Float32Array(outW * outH * d) };
this.mask = new Int32Array(outW * outH * d);
for (let c = 0; c < d; c++) {
for (let y = 0; y < outH; y++) {
for (let x = 0; x < outW; x++) {
let maxVal = -Infinity; let maxIdx = -1;
for (let dy = 0; dy < 2; dy++) {
for (let dx = 0; dx < 2; dx++) {
const idx = (c * h + (y * 2 + dy)) * w + (x * 2 + dx);
const val = input.data[idx];
if (val > maxVal) { maxVal = val; maxIdx = idx; }
}
}
const outIdx = (c * outH + y) * outW + x;
this.output.data[outIdx] = maxVal; this.mask[outIdx] = maxIdx;
}
}
}
return this.output;
}
backward(gradOutput) {
const gradInput = new Float32Array(this.input.data.length).fill(0);
for (let i = 0; i < gradOutput.data.length; i++) gradInput[this.mask[i]] = gradOutput.data[i];
return { ...this.input, data: gradInput };
}
}
class Flatten extends Layer {
forward(input) { this.inputShape = { ...input }; this.output = input.data; return this.output; }
backward(grad) { return { ...this.inputShape, data: grad }; }
}
class Dense extends Layer {
constructor(inSize, outSize) {
super();
this.inSize = inSize; this.outSize = outSize;
const scale = Math.sqrt(2.0 / inSize);
this.weights = new Float32Array(inSize * outSize).map(() => (Math.random() - 0.5) * 2 * scale);
this.biases = new Float32Array(outSize).fill(0);
this.gradW = new Float32Array(this.weights.length); this.gradB = new Float32Array(this.biases.length);
}
forward(input) {
this.input = input; this.output = new Float32Array(this.outSize);
for (let i = 0; i < this.outSize; i++) {
let sum = this.biases[i];
for (let j = 0; j < this.inSize; j++) sum += input[j] * this.weights[i * this.inSize + j];
// Використовуємо Tanh для Bottleneck шару (щоб координати були від -1 до 1), для інших ReLU?
// User просив "як 4 букви", там зазвичай ReLU. Але для красивої візуалізації Tanh краще.
// Залишимо ReLU для стабільності, але для 2-нейронного шару це означає тільки позитивний квадрант.
// Щоб було по кутах (включаючи мінус), краще звичайний лінійний вихід або Tanh.
// Давайте зробимо ReLU, мережа сама навчиться використовувати [0, max].
this.output[i] = sum > 0 ? sum : 0;
}
return this.output;
}
backward(grad) {
const gradIn = new Float32Array(this.inSize).fill(0);
this.gradW.fill(0); this.gradB.fill(0);
for (let i = 0; i < this.outSize; i++) {
let chain = grad[i];
if (this.output[i] <= 0) chain = 0; // ReLU derivative
this.gradB[i] += chain;
for (let j = 0; j < this.inSize; j++) {
this.gradW[i * this.inSize + j] += this.input[j] * chain;
gradIn[j] += this.weights[i * this.inSize + j] * chain;
}
}
return gradIn;
}
}
class SoftmaxLayer extends Layer {
forward(input) {
this.input = input; const max = Math.max(...input);
const exps = input.map(v => Math.exp(v - max));
const sum = exps.reduce((a, b) => a + b, 0);
this.output = exps.map(v => v / sum);
return this.output;
}
backward(labelIndex) {
const grad = new Float32Array(this.output);
grad[labelIndex] -= 1; return grad;
}
}
class CNN {
constructor() {
this.layers = [
new Conv2D(1, 4, 3), // 32x32 -> 30x30x4
new MaxPool2x2(), // 30x30x4 -> 15x15x4
new Flatten(), // 15*15*4 = 900
new Dense(900, 2), // <--- BOTTLENECK: Стискаємо до 2 координат (X, Y)
new Dense(2, 4), // 2 -> 4 Класи
new SoftmaxLayer()
];
this.learningRate = 0.005; // Трохи менший рейт для bottleneck
}
// Повний прохід для отримання класифікації
forward(inputData) {
let x = { w: 32, h: 32, d: 1, data: inputData };
for (const layer of this.layers) x = layer.forward(x);
return x;
}
// Отримання координат з латентного шару (для візуалізації)
getLatent(inputData) {
let x = { w: 32, h: 32, d: 1, data: inputData };
// Проходимо до 4-го шару (Dense 900->2) включно
// layers indices: 0:Conv, 1:Pool, 2:Flat, 3:Dense(2), 4:Dense(4), 5:Softmax
x = this.layers[0].forward(x);
x = this.layers[1].forward(x);
x = this.layers[2].forward(x);
x = this.layers[3].forward(x);
return x; // Повертає масив з 2 чисел
}
train(inputData, labelIndex) {
const output = this.forward(inputData);
let grad = labelIndex;
for (let i = this.layers.length - 1; i >= 0; i--) grad = this.layers[i].backward(grad);
// SGD Update
for (const layer of this.layers) {
if (layer.weights) {
for (let i = 0; i < layer.weights.length; i++) layer.weights[i] -= layer.gradW[i] * this.learningRate;
for (let i = 0; i < layer.biases.length; i++) layer.biases[i] -= layer.gradB[i] * this.learningRate;
}
if (layer.filters) {
for (let i = 0; i < layer.filters.length; i++) layer.filters[i] -= layer.gradFilters[i] * this.learningRate;
for (let i = 0; i < layer.biases.length; i++) layer.biases[i] -= layer.gradBiases[i] * this.learningRate;
}
}
return -Math.log(output[labelIndex] + 1e-7);
}
}
/**
* === ЧАСТИНА 2: Аудіо, Mel-Spectrum, Noise Gate ===
*/
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();
// Збільшуємо FFT для кращої роздільної здатності Mel
analyser.fftSize = 512; // 256 bins
analyser.smoothingTimeConstant = 0.2;
let isListening = false;
let isRecording = false;
let samples = [];
const labels = ["Стоп", "Вперед", "Праворуч", "Ліворуч"];
const colors = ['#ef4444', '#3b82f6', '#f59e0b', '#22c55e']; // Red, Blue, Orange, Green
const SPECTRO_SIZE = 32;
let spectroBuffer = [];
let currentVolume = 0;
// --- MEL FILTER BANK SETUP ---
// Створюємо мапу перетворення лінійних бінiв (0..255) в 32 Mel біни
const MEL_BINS = 32;
const SAMPLE_RATE = audioCtx.sampleRate;
const FFT_SIZE = analyser.fftSize;
const FREQ_MAX = SAMPLE_RATE / 2;
const melMap = [];
function hzToMel(hz) { return 2595 * Math.log10(1 + hz / 700); }
function melToHz(mel) { return 700 * (Math.pow(10, mel / 2595) - 1); }
function createMelFilterBank() {
const minMel = hzToMel(0);
const maxMel = hzToMel(FREQ_MAX); // Або обмежити до 8000Hz для голосу
// Центри Mel фільтрів
const points = [];
for(let i=0; i < MEL_BINS + 2; i++) {
points.push(melToHz(minMel + (i / (MEL_BINS + 1)) * (maxMel - minMel)));
}
// Для кожного Mel біна шукаємо відповідні FFT біни
for(let m=0; m < MEL_BINS; m++) {
const center = points[m+1];
const left = points[m];
const right = points[m+2];
const weights = [];
for(let i=0; i < FFT_SIZE/2; i++) {
const freq = i * SAMPLE_RATE / FFT_SIZE;
let w = 0;
if (freq > left && freq < right) {
if (freq <= center) w = (freq - left) / (center - left);
else w = (right - freq) / (right - center);
}
if(w > 0) weights.push({idx: i, w: w});
}
melMap.push(weights);
}
}
createMelFilterBank();
async function initAudio() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const source = audioCtx.createMediaStreamSource(stream);
source.connect(analyser);
drawSpectrogramLoop();
} catch (e) { alert("Mic Error: " + e); }
}
function getMelFrame() {
const data = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(data);
// RMS Volume
let sum = 0;
for(let i=0; i<data.length; i++) sum += data[i]*data[i];
currentVolume = Math.sqrt(sum / data.length) / 255.0;
const bar = document.getElementById('volBar');
if(bar) bar.style.width = Math.min(100, currentVolume * 400) + "%";
// Convert Linear FFT to Mel
const melData = new Float32Array(MEL_BINS);
for(let m=0; m<MEL_BINS; m++) {
let val = 0;
for(let wObj of melMap[m]) {
val += (data[wObj.idx] / 255.0) * wObj.w;
}
// Log compression (log-mel) makes features more robust
melData[m] = Math.log10(val + 1) * 2; // scale up a bit
}
return melData;
}
function drawSpectrogramLoop() {
const frame = getMelFrame();
if (isRecording) {
spectroBuffer.push(frame);
if(spectroBuffer.length > SPECTRO_SIZE * 2) spectroBuffer.shift();
}
else if (isListening) {
spectroBuffer.push(frame);
if(spectroBuffer.length > SPECTRO_SIZE) spectroBuffer.shift();
if(spectroBuffer.length === SPECTRO_SIZE && Math.random() < 0.2) predictLive();
}
else {
drawSpectroCanvas([frame], true);
requestAnimationFrame(drawSpectrogramLoop);
return;
}
drawSpectroCanvas(spectroBuffer);
requestAnimationFrame(drawSpectrogramLoop);
}
function drawSpectroCanvas(buffer, isSingleLine=false) {
const cvs = document.getElementById('spectrogramCanvas');
const ctx = cvs.getContext('2d');
const w = cvs.width; const h = cvs.height;
ctx.clearRect(0,0,w,h);
if(isSingleLine) {
const col = buffer[0];
for(let i=0; i<col.length; i++) {
const val = Math.min(1, col[i]) * 255;
ctx.fillStyle = `rgb(${val},${val},${val})`;
ctx.fillRect(0, h-i*(h/32), w, h/32);
}
return;
}
const cellW = w / SPECTRO_SIZE;
const cellH = h / 32;
const startIdx = Math.max(0, buffer.length - SPECTRO_SIZE);
for (let t = 0; t < Math.min(buffer.length, SPECTRO_SIZE); t++) {
const col = buffer[startIdx + t];
for (let f = 0; f < col.length; f++) {
const val = Math.min(1, col[f]) * 255;
// Mel spectro usually visualized "hot"
ctx.fillStyle = `rgb(${val}, ${val*0.5}, ${255-val})`;
ctx.fillRect(t * cellW, h - ((f+1) * cellH), cellW, cellH);
}
}
}
// === RECORDING ===
function startRec(labelId) {
if (audioCtx.state === 'suspended') { audioCtx.resume(); }
isRecording = true; spectroBuffer = [];
document.getElementById(`btnRec${labelId}`).classList.add('recording');
}
function stopRec() {
if (!isRecording) return;
isRecording = false;
let labelId = -1;
for(let i=0; i<4; i++) {
const btn = document.getElementById(`btnRec${i}`);
if(btn.classList.contains('recording')) {
btn.classList.remove('recording');
labelId = i;
}
}
if (labelId !== -1 && spectroBuffer.length >= 8) {
const fullData = new Float32Array(SPECTRO_SIZE * 32).fill(0);
const len = Math.min(spectroBuffer.length, SPECTRO_SIZE);
const start = spectroBuffer.length - len;
for(let t=0; t<len; t++) {
const targetT = SPECTRO_SIZE - len + t;
for(let f=0; f<32; f++) fullData[targetT * 32 + f] = spectroBuffer[start + t][f];
}
samples.push({ data: fullData, label: labelId });
document.getElementById(`cnt${labelId}`).innerText = samples.filter(s => s.label === labelId).length;
}
}
/**
* === ЧАСТИНА 3: Навчання та Візуалізація Latent Space ===
*/
let net = new CNN();
async function trainNetwork() {
if (samples.length < 4) { alert("Мало даних! Запишіть слова."); return; }
const btn = document.getElementById('btnTrain');
btn.disabled = true; btn.innerText = "Навчання...";
const EPOCHS = 60;
const lossHistory = [];
// Setup Latent Plot
const tracePrototype = { mode: 'markers', type: 'scatter', marker: { size: 8 } };
const layout = {
margin: {t:10,l:30,r:10,b:20},
paper_bgcolor:'rgba(0,0,0,0)', plot_bgcolor:'rgba(0,0,0,0)',
xaxis:{showgrid:true, gridcolor:'#334155', color:'#94a3b8'},
yaxis:{showgrid:true, gridcolor:'#334155', color:'#94a3b8'}
};
Plotly.newPlot('latent-plot', [], layout);
for (let e = 0; e < EPOCHS; e++) {
let totalLoss = 0;
samples.sort(() => Math.random() - 0.5);
// Arrays for visualization
const latentX = [[],[],[],[]];
const latentY = [[],[],[],[]];
for (const s of samples) {
// Train
totalLoss += net.train(s.data, s.label);
// Visualize (Get latent coords 2D)
const coords = net.getLatent(s.data);
latentX[s.label].push(coords[0]);
latentY[s.label].push(coords[1]);
}
lossHistory.push(totalLoss / samples.length);
// Update Visualization every 5 epochs
if (e % 2 === 0 || e === EPOCHS-1) {
// Loss Plot
Plotly.newPlot('loss-plot', [{ y: lossHistory, type: 'scatter', mode: 'lines', line: {color:'#fff'} }],
{ margin: {t:10,l:30,r:10,b:20}, height: 80, paper_bgcolor:'rgba(0,0,0,0)', plot_bgcolor:'rgba(0,0,0,0)' });
// Latent Plot
const traces = labels.map((lbl, i) => ({
x: latentX[i], y: latentY[i],
mode: 'markers', type: 'scatter',
name: lbl, marker: { color: colors[i], size: 8 }
}));
Plotly.react('latent-plot', traces, layout);
await new Promise(r => setTimeout(r, 10));
}
}
btn.disabled = false; btn.innerText = "🚀 Навчити (Bottleneck)";
}
function predictLive() {
const gateVal = parseInt(document.getElementById('noiseGate').value) / 100.0;
const normalizedVol = Math.min(1.0, currentVolume * 4);
if (normalizedVol < gateVal) {
updatePredUI(new Float32Array(4).fill(0), true);
return;
}
const input = new Float32Array(SPECTRO_SIZE * 32).fill(0);
const snippet = spectroBuffer.slice(spectroBuffer.length - SPECTRO_SIZE);
for(let t=0; t<SPECTRO_SIZE; t++) {
for(let f=0; f<32; f++) input[t * 32 + f] = snippet[t][f];
}
const probs = net.forward(input);
updatePredUI(probs, false);
const maxIdx = probs.indexOf(Math.max(...probs));
if (probs[maxIdx] > 0.6) handleVoiceCommand(maxIdx);
}
function updatePredUI(probs, isSilence) {
const container = document.getElementById('predictions');
container.innerHTML = '';
if(isSilence) {
labels.forEach(l => {
container.innerHTML += `<div class="pred-row disabled"><span style="width:70px">${l}</span><div class="bar-bg"></div></div>`;
});
return;
}
const maxIdx = probs.indexOf(Math.max(...probs));
probs.forEach((p, i) => {
const row = document.createElement('div');
row.className = `pred-row ${i === maxIdx && p > 0.6 ? 'active' : ''}`;
row.innerHTML = `<span style="width:70px">${labels[i]}</span><div class="bar-bg"><div class="bar-fill" style="width:${p*100}%"></div></div><span style="width:30px">${(p*100).toFixed(0)}%</span>`;
container.appendChild(row);
});
}
function saveNetwork() {
const data = { w:[], b:[], f:[] };
net.layers.forEach(l => {
if(l.weights) data.w.push(Array.from(l.weights));
if(l.biases) data.b.push(Array.from(l.biases));
if(l.filters) data.f.push(Array.from(l.filters));
});
const a = document.createElement('a');
a.href = URL.createObjectURL(new Blob([JSON.stringify(data)], {type:'application/json'}));
a.download = 'cnn-voice-mel-bottleneck.json'; a.click();
}
function loadNetwork(input) {
const r = new FileReader();
r.onload = e => {
const d = JSON.parse(e.target.result);
let wi=0, bi=0, fi=0;
net.layers.forEach(l => {
if(l.weights) l.weights.set(d.w[wi++]);
if(l.biases) l.biases.set(d.b[bi++]);
if(l.filters) l.filters.set(d.f[fi++]);
});
alert("Завантажено!");
};
r.readAsText(input.files[0]);
}
/**
* === ЧАСТИНА 4: Гра Змійка ===
*/
const cvs = document.getElementById('snakeCanvas');
const ctx = cvs.getContext('2d');
let snake = [{x: 10, y: 10}];
let food = {x: 15, y: 15};
let dir = {x: 0, y: -1};
const GRID = 20;
let score = 0;
let momentum = 0.0; const FRICTION = 0.02; let moveAccumulator = 0.0;
window.onresize = () => { cvs.width = cvs.parentElement.clientWidth; cvs.height = cvs.parentElement.clientHeight; };
window.onresize();
function gameLoop() {
if (momentum > 0) { momentum -= FRICTION; if (momentum < 0) momentum = 0; }
document.getElementById('momentumVal').innerText = (momentum * 100).toFixed(0) + "%";
moveAccumulator += momentum;
if (moveAccumulator >= 1.0) { moveAccumulator -= 1.0; moveSnake(); }
drawGame();
}
function moveSnake() {
const head = {x: snake[0].x + dir.x, y: snake[0].y + dir.y};
const tw = Math.floor(cvs.width/GRID), th = Math.floor(cvs.height/GRID);
if (head.x < 0) head.x = tw - 1; if (head.x >= tw) head.x = 0;
if (head.y < 0) head.y = th - 1; if (head.y >= th) head.y = 0;
if (snake.some(s => s.x===head.x && s.y===head.y)) return resetGame();
snake.unshift(head);
if (head.x===food.x && head.y===food.y) {
score++; document.getElementById('scoreVal').innerText = score;
food = {x: Math.floor(Math.random()*tw), y: Math.floor(Math.random()*th)};
momentum = Math.min(1.5, momentum + 0.2);
} else snake.pop();
}
function drawGame() {
ctx.fillStyle = '#0f172a'; ctx.fillRect(0,0,cvs.width,cvs.height);
ctx.fillStyle = '#ef4444'; ctx.beginPath(); ctx.arc(food.x*GRID+GRID/2,food.y*GRID+GRID/2,GRID/2-2,0,7); ctx.fill();
ctx.fillStyle = '#22c55e'; snake.forEach((s, i) => { if(i > 0) ctx.fillRect(s.x*GRID+1,s.y*GRID+1,GRID-2,GRID-2); });
const head = snake[0]; const cx = head.x*GRID + GRID/2; const cy = head.y*GRID + GRID/2;
ctx.save(); ctx.translate(cx, cy);
let angle = 0;
if(dir.x === 0 && dir.y === -1) angle = 0;
else if(dir.x === 1 && dir.y === 0) angle = Math.PI/2;
else if(dir.x === 0 && dir.y === 1) angle = Math.PI;
else if(dir.x === -1 && dir.y === 0) angle = -Math.PI/2;
ctx.rotate(angle);
ctx.fillStyle = '#4ade80'; ctx.beginPath(); ctx.moveTo(0, -GRID/2 + 2); ctx.lineTo(GRID/2 - 2, GRID/2 - 2); ctx.lineTo(-GRID/2 + 2, GRID/2 - 2); ctx.closePath(); ctx.fill();
ctx.restore();
}
function resetGame() {
snake = [{x:10,y:10}]; dir={x:0,y:-1}; score=0; momentum=0;
document.getElementById('scoreVal').innerText=0;
document.getElementById('gameOverlay').style.display='block';
}
let lastCmd = 0;
function handleVoiceCommand(i) {
if(Date.now()-lastCmd<300) return; lastCmd=Date.now();
document.getElementById('lastCmd').innerText = labels[i];
document.getElementById('gameOverlay').style.display = 'none';
if (i===1) momentum = 1.0;
else if (i===0) momentum = 0;
else if (i===2) dir = {x: -dir.y, y: dir.x};
else if (i===3) dir = {x: dir.y, y: -dir.x};
}
setInterval(gameLoop, 100);
initAudio();
function toggleListening() {
isListening = !isListening;
document.getElementById('btnListen').innerText = isListening ? "🛑 Стоп слухати" : "🎙️ Старт мікрофону";
if(audioCtx.state === 'suspended') audioCtx.resume();
if (!isListening) momentum = 0;
}
</script>
</body>
</html>