|
|
@@ -0,0 +1,588 @@
|
|
|
+(() => {
|
|
|
+ "use strict";
|
|
|
+ const M = window.GOLOS_MODEL;
|
|
|
+ const SAMPLES = window.GOLOS_SAMPLES || [];
|
|
|
+ const $ = id => document.getElementById(id);
|
|
|
+ const N_FREQ = 64, N_TIME = 44;
|
|
|
+ const state = { probability: null, truth: null, components: null, spec: null, windows: [], selectedWindow: 0, objectUrl: null, currentName: "" };
|
|
|
+
|
|
|
+ if (!M) {
|
|
|
+ $("analysisStatus").textContent = "ОШИБКА: НЕТ МОДЕЛИ";
|
|
|
+ throw new Error("model.js не загружен");
|
|
|
+ }
|
|
|
+
|
|
|
+ $("aucValue").textContent = Number(M.validation.rocAuc).toFixed(3);
|
|
|
+ $("sampleButtons").innerHTML = "";
|
|
|
+ SAMPLES.forEach(sample => {
|
|
|
+ const b = document.createElement("button");
|
|
|
+ b.type = "button";
|
|
|
+ b.className = `sample-btn ${sample.label ? "uav" : "bg"}`;
|
|
|
+ b.innerHTML = `${sample.name}<small>${sample.label ? "МЕТКА: БПЛА" : "МЕТКА: ФОН"}</small>`;
|
|
|
+ b.addEventListener("click", () => {
|
|
|
+ document.querySelectorAll(".sample-btn").forEach(x => x.classList.remove("active"));
|
|
|
+ b.classList.add("active");
|
|
|
+ const bytes = decodeBase64(sample.base64);
|
|
|
+ const db = Float64Array.from(bytes, v => v * 0.3 - 45);
|
|
|
+ const result = predict(db);
|
|
|
+ state.currentName = sample.name;
|
|
|
+ state.spec = bytes;
|
|
|
+ state.truth = sample.label;
|
|
|
+ state.windows = [];
|
|
|
+ state.selectedWindow = 0;
|
|
|
+ $("specSource").textContent = sample.name.toUpperCase();
|
|
|
+ $("featuresSource").textContent = "ОБРАЗЕЦ ИЗ TRAIN.NPZ";
|
|
|
+ $("timelineWrap").hidden = true;
|
|
|
+ $("analysisStatus").textContent = "СПЕКТРОГРАММА ЗАГРУЖЕНА";
|
|
|
+ $("analysisStatus").className = "status-pill ready";
|
|
|
+ $("fileName").textContent = "Выбран встроенный образец обучающей выборки";
|
|
|
+ if (!$("uploadedVideo").hidden) $("uploadedVideo").hidden = true;
|
|
|
+ state.probability = result.probability;
|
|
|
+ state.components = result.components;
|
|
|
+ drawSpectrogram(bytes);
|
|
|
+ drawComponents(result.components);
|
|
|
+ renderDecision();
|
|
|
+ });
|
|
|
+ $("sampleButtons").appendChild(b);
|
|
|
+ });
|
|
|
+
|
|
|
+ $("threshold").addEventListener("input", () => {
|
|
|
+ $("thresholdOut").textContent = Number($("threshold").value).toFixed(2);
|
|
|
+ renderDecision();
|
|
|
+ if (state.windows.length) drawTimeline();
|
|
|
+ });
|
|
|
+
|
|
|
+ $("mediaFile").addEventListener("change", async (event) => {
|
|
|
+ const file = event.target.files && event.target.files[0];
|
|
|
+ if (!file) return;
|
|
|
+ await analyzeFile(file);
|
|
|
+ });
|
|
|
+
|
|
|
+ function decodeBase64(str) {
|
|
|
+ const bin = atob(str);
|
|
|
+ const a = new Uint8Array(bin.length);
|
|
|
+ for (let i = 0; i < bin.length; i++) a[i] = bin.charCodeAt(i);
|
|
|
+ return a;
|
|
|
+ }
|
|
|
+
|
|
|
+ function median(a) {
|
|
|
+ const s = Array.from(a).sort((x, y) => x - y);
|
|
|
+ const n = s.length;
|
|
|
+ return n % 2 ? s[(n - 1) >> 1] : (s[n / 2 - 1] + s[n / 2]) / 2;
|
|
|
+ }
|
|
|
+ function mean(a) { let s = 0; for (const v of a) s += v; return s / a.length; }
|
|
|
+ function std(a, m = mean(a)) {
|
|
|
+ let s = 0; for (const v of a) { const d = v - m; s += d * d; }
|
|
|
+ return Math.sqrt(s / a.length);
|
|
|
+ }
|
|
|
+ function corr(a, b) {
|
|
|
+ if (a.length < 2) return 0;
|
|
|
+ const ma = mean(a), mb = mean(b), sa = std(a, ma), sb = std(b, mb);
|
|
|
+ const den = sa * sb;
|
|
|
+ if (den < 1e-10) return 0;
|
|
|
+ let s = 0; for (let i = 0; i < a.length; i++) s += (a[i] - ma) * (b[i] - mb);
|
|
|
+ return (s / a.length) / den;
|
|
|
+ }
|
|
|
+
|
|
|
+ // Mirrors the 46-feature extraction in solution #2 of "ML1. Голос винта".
|
|
|
+ function extractFeatures(S) {
|
|
|
+ const P = new Float64Array(N_FREQ * N_TIME);
|
|
|
+ const Pn = new Float64Array(N_FREQ * N_TIME);
|
|
|
+ const cent = new Float64Array(N_TIME), bandwidth = new Float64Array(N_TIME);
|
|
|
+ const flatness = new Float64Array(N_TIME), entropy = new Float64Array(N_TIME);
|
|
|
+ const rolloff = new Float64Array(N_TIME), totalEnergy = new Float64Array(N_TIME);
|
|
|
+ const freqIndex = new Float64Array(N_FREQ);
|
|
|
+ for (let f = 0; f < N_FREQ; f++) freqIndex[f] = f;
|
|
|
+
|
|
|
+ // MFCC: DCT-II over frequency for each time frame, after per-frame centering.
|
|
|
+ const mfccMean = new Float64Array(13), mfccStd = new Float64Array(13);
|
|
|
+ const mfccRows = Array.from({ length: 13 }, () => new Float64Array(N_TIME));
|
|
|
+ const dctScale = new Float64Array(14);
|
|
|
+ for (let k = 1; k <= 13; k++) dctScale[k] = Math.sqrt(2 / N_FREQ);
|
|
|
+ for (let t = 0; t < N_TIME; t++) {
|
|
|
+ let colMean = 0;
|
|
|
+ for (let f = 0; f < N_FREQ; f++) colMean += S[f * N_TIME + t];
|
|
|
+ colMean /= N_FREQ;
|
|
|
+ for (let k = 1; k <= 13; k++) {
|
|
|
+ let sum = 0;
|
|
|
+ for (let f = 0; f < N_FREQ; f++) {
|
|
|
+ sum += (S[f * N_TIME + t] - colMean) *
|
|
|
+ Math.cos(Math.PI * (f + 0.5) * k / N_FREQ);
|
|
|
+ }
|
|
|
+ mfccRows[k - 1][t] = sum * dctScale[k];
|
|
|
+ }
|
|
|
+ }
|
|
|
+ for (let k = 0; k < 13; k++) {
|
|
|
+ mfccMean[k] = mean(mfccRows[k]);
|
|
|
+ mfccStd[k] = std(mfccRows[k], mfccMean[k]);
|
|
|
+ }
|
|
|
+
|
|
|
+ const eps = 1e-10;
|
|
|
+ let lowEnergy = 0, highEnergy = 0, sumAll = 0;
|
|
|
+ for (let t = 0; t < N_TIME; t++) {
|
|
|
+ let frameSum = 0;
|
|
|
+ for (let f = 0; f < N_FREQ; f++) {
|
|
|
+ const v = Math.pow(10, S[f * N_TIME + t] / 10);
|
|
|
+ P[f * N_TIME + t] = v;
|
|
|
+ frameSum += v;
|
|
|
+ }
|
|
|
+ frameSum += eps;
|
|
|
+ totalEnergy[t] = frameSum - eps;
|
|
|
+ sumAll += frameSum - eps;
|
|
|
+ let c = 0, b = 0, logsum = 0, logsum2 = 0;
|
|
|
+ for (let f = 0; f < N_FREQ; f++) {
|
|
|
+ const ix = f * N_TIME + t;
|
|
|
+ const pn = P[ix] / frameSum;
|
|
|
+ Pn[ix] = pn;
|
|
|
+ c += f * pn;
|
|
|
+ const lp = Math.log(pn + eps);
|
|
|
+ logsum += lp;
|
|
|
+ logsum2 += pn * lp;
|
|
|
+ if (f < 16) lowEnergy += P[ix];
|
|
|
+ if (f >= 32) highEnergy += P[ix];
|
|
|
+ }
|
|
|
+ cent[t] = c;
|
|
|
+ for (let f = 0; f < N_FREQ; f++) {
|
|
|
+ const d = f - c; b += d * d * Pn[f * N_TIME + t];
|
|
|
+ }
|
|
|
+ bandwidth[t] = Math.sqrt(b);
|
|
|
+ const gm = Math.exp(logsum / N_FREQ);
|
|
|
+ const am = 1 / N_FREQ;
|
|
|
+ flatness[t] = gm / (am + eps);
|
|
|
+ entropy[t] = -logsum2 / Math.log(N_FREQ);
|
|
|
+ let cumulative = 0, idx = 0;
|
|
|
+ for (let f = 0; f < N_FREQ; f++) {
|
|
|
+ cumulative += Pn[f * N_TIME + t];
|
|
|
+ if (cumulative >= 0.85) { idx = f; break; }
|
|
|
+ }
|
|
|
+ rolloff[t] = idx / 63;
|
|
|
+ }
|
|
|
+
|
|
|
+ const ac1a = [], ac1b = [], ac2a = [], ac2b = [];
|
|
|
+ const normalizedEnergy = Array.from(totalEnergy, v => v / (mean(totalEnergy) + eps));
|
|
|
+ for (let t = 0; t < N_TIME - 1; t++) { ac1a.push(normalizedEnergy[t]); ac1b.push(normalizedEnergy[t + 1]); }
|
|
|
+ for (let t = 0; t < N_TIME - 2; t++) { ac2a.push(normalizedEnergy[t]); ac2b.push(normalizedEnergy[t + 2]); }
|
|
|
+ const ac1 = corr(ac1a, ac1b), ac2 = corr(ac2a, ac2b);
|
|
|
+ const envMean = mean(normalizedEnergy);
|
|
|
+ let zcrSum = 0, prevSign = Math.sign(normalizedEnergy[0] - envMean);
|
|
|
+ for (let t = 1; t < N_TIME; t++) {
|
|
|
+ const sign = Math.sign(normalizedEnergy[t] - envMean);
|
|
|
+ zcrSum += Math.abs(sign - prevSign);
|
|
|
+ prevSign = sign;
|
|
|
+ }
|
|
|
+ const zcr = zcrSum / (2 * (N_TIME - 1));
|
|
|
+ const total = sumAll + eps;
|
|
|
+ const lowRatio = lowEnergy / total, highRatio = highEnergy / total;
|
|
|
+
|
|
|
+ const rowStats = [];
|
|
|
+ const flatSn = new Float64Array(N_FREQ * N_TIME);
|
|
|
+ for (let f = 0; f < N_FREQ; f++) {
|
|
|
+ const row = new Float64Array(N_TIME);
|
|
|
+ for (let t = 0; t < N_TIME; t++) row[t] = S[f * N_TIME + t];
|
|
|
+ const med = median(row);
|
|
|
+ for (let t = 0; t < N_TIME; t++) flatSn[f * N_TIME + t] = row[t] - med;
|
|
|
+ rowStats.push(row);
|
|
|
+ }
|
|
|
+ let m = 0;
|
|
|
+ for (const v of flatSn) m += v;
|
|
|
+ m /= flatSn.length;
|
|
|
+ const s = std(flatSn);
|
|
|
+ let m3 = 0, m4 = 0;
|
|
|
+ for (const v of flatSn) {
|
|
|
+ const d = v - m; m3 += d ** 3; m4 += d ** 4;
|
|
|
+ }
|
|
|
+ m3 /= flatSn.length; m4 /= flatSn.length;
|
|
|
+ const kurt = m4 / (s ** 4 + eps) - 3;
|
|
|
+ const skew = m3 / (s ** 3 + eps);
|
|
|
+
|
|
|
+ const freqVar = new Float64Array(N_FREQ), freqRange = new Float64Array(N_FREQ);
|
|
|
+ for (let f = 0; f < N_FREQ; f++) {
|
|
|
+ let sm = 0, mn = Infinity, mx = -Infinity;
|
|
|
+ for (let t = 0; t < N_TIME; t++) {
|
|
|
+ const v = flatSn[f * N_TIME + t];
|
|
|
+ sm += v; if (v < mn) mn = v; if (v > mx) mx = v;
|
|
|
+ }
|
|
|
+ const rm = sm / N_TIME;
|
|
|
+ let vv = 0;
|
|
|
+ for (let t = 0; t < N_TIME; t++) {
|
|
|
+ const d = flatSn[f * N_TIME + t] - rm; vv += d * d;
|
|
|
+ }
|
|
|
+ freqVar[f] = vv / N_TIME;
|
|
|
+ freqRange[f] = mx - mn;
|
|
|
+ }
|
|
|
+
|
|
|
+ const f = [
|
|
|
+ ...mfccMean, ...mfccStd,
|
|
|
+ mean(cent), std(cent),
|
|
|
+ mean(bandwidth), std(bandwidth),
|
|
|
+ mean(rolloff),
|
|
|
+ mean(flatness), std(flatness),
|
|
|
+ mean(entropy), std(entropy),
|
|
|
+ ac1, ac2, zcr,
|
|
|
+ lowRatio, highRatio,
|
|
|
+ kurt, skew,
|
|
|
+ mean(freqVar), std(freqVar),
|
|
|
+ mean(freqRange), std(freqRange)
|
|
|
+ ];
|
|
|
+ return f;
|
|
|
+ }
|
|
|
+
|
|
|
+ function predict(dbArray) {
|
|
|
+ const raw = extractFeatures(dbArray);
|
|
|
+ const norm = raw.map((v, i) => (v - M.rawMean[i]) / M.rawStd[i]);
|
|
|
+ const pcs = new Array(16);
|
|
|
+ for (let k = 0; k < 16; k++) {
|
|
|
+ let sum = 0;
|
|
|
+ for (let j = 0; j < norm.length; j++) sum += norm[j] * M.components[k][j];
|
|
|
+ pcs[k] = (sum - M.projectionMean[k]) / M.projectionStd[k];
|
|
|
+ }
|
|
|
+ let z = M.intercept;
|
|
|
+ for (let k = 0; k < 16; k++) z += pcs[k] * M.coef[k];
|
|
|
+ const p = 1 / (1 + Math.exp(-Math.max(-40, Math.min(40, z))));
|
|
|
+ return { probability: p, components: pcs, raw };
|
|
|
+ }
|
|
|
+
|
|
|
+ function colorMap(v) {
|
|
|
+ const stops = [
|
|
|
+ [0.00, [3, 13, 38]], [0.20, [0, 54, 110]], [0.40, [0, 154, 174]],
|
|
|
+ [0.60, [76, 205, 151]], [0.78, [246, 218, 72]], [0.90, [246, 111, 43]], [1.00, [245, 42, 55]]
|
|
|
+ ];
|
|
|
+ let a = stops[0], b = stops[stops.length - 1];
|
|
|
+ for (let i = 0; i < stops.length - 1; i++) {
|
|
|
+ if (v >= stops[i][0] && v <= stops[i + 1][0]) { a = stops[i]; b = stops[i + 1]; break; }
|
|
|
+ }
|
|
|
+ const t = (v - a[0]) / (b[0] - a[0] || 1);
|
|
|
+ return a[1].map((c, i) => Math.round(c + (b[1][i] - c) * t));
|
|
|
+ }
|
|
|
+
|
|
|
+ function drawSpectrogram(bytes) {
|
|
|
+ const canvas = $("spectrogram"), ctx = canvas.getContext("2d");
|
|
|
+ const w = canvas.width, h = canvas.height;
|
|
|
+ ctx.fillStyle = "#06101b"; ctx.fillRect(0, 0, w, h);
|
|
|
+ let mn = 255, mx = 0;
|
|
|
+ for (const v of bytes) { if (v < mn) mn = v; if (v > mx) mx = v; }
|
|
|
+ const range = Math.max(1, mx - mn);
|
|
|
+ const cellW = w / N_TIME, cellH = h / N_FREQ;
|
|
|
+ for (let f = 0; f < N_FREQ; f++) {
|
|
|
+ for (let t = 0; t < N_TIME; t++) {
|
|
|
+ const v = bytes[f * N_TIME + t];
|
|
|
+ const c = colorMap((v - mn) / range);
|
|
|
+ ctx.fillStyle = `rgb(${c[0]},${c[1]},${c[2]})`;
|
|
|
+ ctx.fillRect(t * cellW, h - (f + 1) * cellH, Math.ceil(cellW + .3), Math.ceil(cellH + .3));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ ctx.strokeStyle = "rgba(205,235,245,.14)"; ctx.lineWidth = 1;
|
|
|
+ for (let i = 1; i < 4; i++) { ctx.beginPath(); ctx.moveTo(0, h * i / 4); ctx.lineTo(w, h * i / 4); ctx.stroke(); }
|
|
|
+ for (let i = 1; i < 4; i++) { ctx.beginPath(); ctx.moveTo(w * i / 4, 0); ctx.lineTo(w * i / 4, h); ctx.stroke(); }
|
|
|
+ }
|
|
|
+
|
|
|
+ function drawComponents(pcs) {
|
|
|
+ const root = $("componentBars"); root.innerHTML = "";
|
|
|
+ const max = Math.max(0.1, ...pcs.map(Math.abs));
|
|
|
+ pcs.forEach((value, i) => {
|
|
|
+ const el = document.createElement("div"); el.className = "comp";
|
|
|
+ const pct = Math.max(2, Math.round(Math.abs(value) / max * 100));
|
|
|
+ el.innerHTML = `<span class="comp-val">${value.toFixed(1)}</span><div class="comp-track"><div class="comp-fill" style="height:${pct}%;${value < 0 ? "background:linear-gradient(0deg,#a86c54,#e5b56a)" : ""}"></div></div><small>PC${i + 1}</small>`;
|
|
|
+ root.appendChild(el);
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ function renderDecision() {
|
|
|
+ const threshold = Number($("threshold").value);
|
|
|
+ const p = state.probability;
|
|
|
+ $("thresholdOut").textContent = threshold.toFixed(2);
|
|
|
+ if (p == null) return;
|
|
|
+ const positive = p >= threshold;
|
|
|
+ $("decisionLabel").textContent = positive ? "БПЛА ОБНАРУЖЕН" : "ФОН";
|
|
|
+ $("decisionLabel").className = "decision-label" + (positive ? " drone" : "");
|
|
|
+ $("probText").textContent = (p * 100).toFixed(1) + "%";
|
|
|
+ $("bgText").textContent = ((1 - p) * 100).toFixed(1) + "%";
|
|
|
+ $("probBar").style.width = (p * 100) + "%";
|
|
|
+ $("bgBar").style.width = ((1 - p) * 100) + "%";
|
|
|
+ const explanation = positive
|
|
|
+ ? "Оценка класса БПЛА достигла порога. Система формирует отметку обнаружения."
|
|
|
+ : "Оценка класса БПЛА ниже порога. Система относит запись к фоновому классу.";
|
|
|
+ $("decisionExplanation").textContent = explanation + " Измените порог и наблюдайте, как меняется решение.";
|
|
|
+ const truth = $("truthBadge");
|
|
|
+ if (state.truth != null) {
|
|
|
+ truth.hidden = false;
|
|
|
+ const correct = (positive ? 1 : 0) === state.truth;
|
|
|
+ truth.className = "truth-badge " + (correct ? "good" : "bad");
|
|
|
+ truth.textContent = `Исходная метка: ${state.truth ? "БПЛА" : "ФОН"} · ${correct ? "Решение совпало с меткой" : "Решение не совпало с меткой"}`;
|
|
|
+ } else {
|
|
|
+ truth.hidden = true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ function resampleLinear(src, sourceRate, targetRate) {
|
|
|
+ if (sourceRate === targetRate) return src;
|
|
|
+ const len = Math.max(1, Math.floor(src.length * targetRate / sourceRate));
|
|
|
+ const dst = new Float32Array(len);
|
|
|
+ const ratio = sourceRate / targetRate;
|
|
|
+ for (let i = 0; i < len; i++) {
|
|
|
+ const pos = i * ratio, left = Math.floor(pos), frac = pos - left;
|
|
|
+ const a = src[Math.min(left, src.length - 1)];
|
|
|
+ const b = src[Math.min(left + 1, src.length - 1)];
|
|
|
+ dst[i] = a + (b - a) * frac;
|
|
|
+ }
|
|
|
+ return dst;
|
|
|
+ }
|
|
|
+
|
|
|
+ function fft(re, im) {
|
|
|
+ const n = re.length;
|
|
|
+ let j = 0;
|
|
|
+ for (let i = 1; i < n; i++) {
|
|
|
+ let bit = n >> 1;
|
|
|
+ while (j & bit) { j ^= bit; bit >>= 1; }
|
|
|
+ j ^= bit;
|
|
|
+ if (i < j) {
|
|
|
+ [re[i], re[j]] = [re[j], re[i]];
|
|
|
+ [im[i], im[j]] = [im[j], im[i]];
|
|
|
+ }
|
|
|
+ }
|
|
|
+ for (let len = 2; len <= n; len <<= 1) {
|
|
|
+ const angle = -2 * Math.PI / len;
|
|
|
+ const wlenR = Math.cos(angle), wlenI = Math.sin(angle);
|
|
|
+ for (let i = 0; i < n; i += len) {
|
|
|
+ let wr = 1, wi = 0;
|
|
|
+ for (let k = 0; k < len / 2; k++) {
|
|
|
+ const uR = re[i + k], uI = im[i + k];
|
|
|
+ const vR = re[i + k + len / 2] * wr - im[i + k + len / 2] * wi;
|
|
|
+ const vI = re[i + k + len / 2] * wi + im[i + k + len / 2] * wr;
|
|
|
+ re[i + k] = uR + vR; im[i + k] = uI + vI;
|
|
|
+ re[i + k + len / 2] = uR - vR; im[i + k + len / 2] = uI - vI;
|
|
|
+ const nextWr = wr * wlenR - wi * wlenI;
|
|
|
+ wi = wr * wlenI + wi * wlenR; wr = nextWr;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ const melBank = (() => {
|
|
|
+ const sr = 16000, nfft = 1024, bins = nfft / 2 + 1, filters = [];
|
|
|
+ const hzToMel = hz => 2595 * Math.log10(1 + hz / 700);
|
|
|
+ const melToHz = mel => 700 * (Math.pow(10, mel / 2595) - 1);
|
|
|
+ const low = hzToMel(30), high = hzToMel(8000);
|
|
|
+ const edges = Array.from({ length: 66 }, (_, i) => melToHz(low + (high - low) * i / 65));
|
|
|
+ for (let m = 0; m < 64; m++) {
|
|
|
+ const row = new Float64Array(bins);
|
|
|
+ const a = edges[m], b = edges[m + 1], c = edges[m + 2];
|
|
|
+ let first = bins, last = 0;
|
|
|
+ for (let k = 0; k < bins; k++) {
|
|
|
+ const f = k * sr / nfft;
|
|
|
+ row[k] = f < a || f > c ? 0 : f <= b ? (f - a) / (b - a) : (c - f) / (c - b);
|
|
|
+ if (row[k] > 0) { first = Math.min(first, k); last = k; }
|
|
|
+ }
|
|
|
+ filters.push({ weights: row, first, last });
|
|
|
+ }
|
|
|
+ return filters;
|
|
|
+ })();
|
|
|
+
|
|
|
+ function makeAudioSpectrogram(audio, startSample) {
|
|
|
+ const sr = 16000, nfft = 1024, frameCount = 44, need = sr;
|
|
|
+ const segment = new Float32Array(need);
|
|
|
+ for (let i = 0; i < need; i++) segment[i] = audio[startSample + i] || 0;
|
|
|
+ const energies = new Float64Array(64 * frameCount);
|
|
|
+ const starts = Array.from({ length: frameCount }, (_, i) => Math.round(i * (need - nfft) / (frameCount - 1)));
|
|
|
+ const hann = new Float64Array(nfft);
|
|
|
+ for (let i = 0; i < nfft; i++) hann[i] = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / (nfft - 1));
|
|
|
+ let globalMax = 1e-15;
|
|
|
+ for (let t = 0; t < frameCount; t++) {
|
|
|
+ const re = new Float64Array(nfft), im = new Float64Array(nfft);
|
|
|
+ const start = starts[t];
|
|
|
+ for (let i = 0; i < nfft; i++) re[i] = segment[start + i] * hann[i];
|
|
|
+ fft(re, im);
|
|
|
+ const power = new Float64Array(nfft / 2 + 1);
|
|
|
+ for (let k = 0; k < power.length; k++) power[k] = (re[k] * re[k] + im[k] * im[k]) / (nfft * nfft);
|
|
|
+ for (let f = 0; f < 64; f++) {
|
|
|
+ let e = 0; const filter = melBank[f];
|
|
|
+ for (let k = filter.first; k <= filter.last; k++) e += power[k] * filter.weights[k];
|
|
|
+ energies[f * frameCount + t] = e;
|
|
|
+ if (e > globalMax) globalMax = e;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ const bytes = new Uint8Array(64 * 44);
|
|
|
+ for (let i = 0; i < energies.length; i++) {
|
|
|
+ let db = 10 * Math.log10(Math.max(energies[i], 1e-15) / globalMax);
|
|
|
+ db = Math.max(-45, Math.min(31.5, db));
|
|
|
+ bytes[i] = Math.max(0, Math.min(255, Math.round((db + 45) / 0.3)));
|
|
|
+ }
|
|
|
+ return bytes;
|
|
|
+ }
|
|
|
+
|
|
|
+ async function analyzeFile(file) {
|
|
|
+ $("analysisStatus").textContent = "ОБРАБОТКА...";
|
|
|
+ $("analysisStatus").className = "status-pill busy";
|
|
|
+ $("fileName").textContent = file.name;
|
|
|
+ $("truthBadge").hidden = true;
|
|
|
+ $("timelineWrap").hidden = true;
|
|
|
+ state.truth = null; state.windows = [];
|
|
|
+ const vid = $("uploadedVideo");
|
|
|
+ if (state.objectUrl) URL.revokeObjectURL(state.objectUrl);
|
|
|
+ state.objectUrl = URL.createObjectURL(file);
|
|
|
+ if (file.type.startsWith("video/")) {
|
|
|
+ vid.src = state.objectUrl; vid.hidden = false;
|
|
|
+ } else {
|
|
|
+ vid.hidden = true; vid.removeAttribute("src");
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ const AudioCtx = window.AudioContext || window.webkitAudioContext;
|
|
|
+ if (!AudioCtx) throw new Error("Браузер не поддерживает Web Audio API.");
|
|
|
+ const audioCtx = new AudioCtx();
|
|
|
+ const bytes = await file.arrayBuffer();
|
|
|
+ let buffer;
|
|
|
+ try { buffer = await audioCtx.decodeAudioData(bytes.slice(0)); }
|
|
|
+ catch { await audioCtx.close(); throw new Error("Не удалось прочитать звуковую дорожку. Попробуйте WAV, MP3 или отдельный аудиофайл, извлечённый из видео."); }
|
|
|
+ const length = buffer.length;
|
|
|
+ const mono = new Float32Array(length);
|
|
|
+ for (let ch = 0; ch < buffer.numberOfChannels; ch++) {
|
|
|
+ const data = buffer.getChannelData(ch);
|
|
|
+ for (let i = 0; i < length; i++) mono[i] += data[i] / buffer.numberOfChannels;
|
|
|
+ }
|
|
|
+ const audio = resampleLinear(mono, buffer.sampleRate, 16000);
|
|
|
+ await audioCtx.close();
|
|
|
+ if (audio.length < 4000) throw new Error("В файле слишком короткая звуковая дорожка.");
|
|
|
+ const duration = audio.length / 16000;
|
|
|
+ const hop = 0.5, count = Math.min(80, Math.max(1, Math.floor((duration - 1) / hop) + 1));
|
|
|
+ const windows = [];
|
|
|
+ for (let i = 0; i < count; i++) {
|
|
|
+ const start = Math.round(i * hop * 16000);
|
|
|
+ const bytesSpec = makeAudioSpectrogram(audio, start);
|
|
|
+ const db = Float64Array.from(bytesSpec, v => v * 0.3 - 45);
|
|
|
+ const result = predict(db);
|
|
|
+ windows.push({ start: i * hop, probability: result.probability, spec: bytesSpec, components: result.components });
|
|
|
+ if (i % 4 === 3) await new Promise(resolve => setTimeout(resolve, 0));
|
|
|
+ }
|
|
|
+ state.windows = windows;
|
|
|
+ const bestIndex = windows.reduce((best, w, i) => w.probability > windows[best].probability ? i : best, 0);
|
|
|
+ state.selectedWindow = bestIndex;
|
|
|
+ selectWindow(bestIndex);
|
|
|
+ $("timelineWrap").hidden = windows.length < 2;
|
|
|
+ $("timelineLabel").textContent = `${windows.length} окон · шаг 0,5 с · длительность ${duration.toFixed(1)} с`;
|
|
|
+ drawTimeline();
|
|
|
+ $("analysisStatus").textContent = "АНАЛИЗ ЗАВЕРШЁН";
|
|
|
+ $("analysisStatus").className = "status-pill ready";
|
|
|
+ } catch (err) {
|
|
|
+ $("analysisStatus").textContent = "ОШИБКА ЧТЕНИЯ";
|
|
|
+ $("analysisStatus").className = "status-pill";
|
|
|
+ $("decisionLabel").textContent = "НЕТ РЕЗУЛЬТАТА";
|
|
|
+ $("decisionLabel").className = "decision-label empty";
|
|
|
+ $("decisionExplanation").textContent = err && err.message ? err.message : "Не удалось обработать запись.";
|
|
|
+ $("probText").textContent = $("bgText").textContent = "—";
|
|
|
+ $("probBar").style.width = $("bgBar").style.width = "0%";
|
|
|
+ $("spectrogram").getContext("2d").clearRect(0, 0, 704, 300);
|
|
|
+ $("componentBars").innerHTML = '<div class="empty-features">Нет данных для отображения.</div>';
|
|
|
+ state.probability = null;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ function selectWindow(index) {
|
|
|
+ const w = state.windows[index];
|
|
|
+ if (!w) return;
|
|
|
+ state.selectedWindow = index;
|
|
|
+ state.probability = w.probability;
|
|
|
+ state.truth = null;
|
|
|
+ state.spec = w.spec;
|
|
|
+ state.components = w.components;
|
|
|
+ $("specSource").textContent = `ФРАГМЕНТ ${index + 1} · ${w.start.toFixed(1)} С`;
|
|
|
+ $("featuresSource").textContent = `ОКНО ${index + 1}/${state.windows.length}`;
|
|
|
+ drawSpectrogram(w.spec);
|
|
|
+ drawComponents(w.components);
|
|
|
+ renderDecision();
|
|
|
+ if (state.windows.length) drawTimeline();
|
|
|
+ }
|
|
|
+
|
|
|
+ function drawTimeline() {
|
|
|
+ const canvas = $("timeline"), ctx = canvas.getContext("2d");
|
|
|
+ const w = canvas.width, h = canvas.height;
|
|
|
+ ctx.fillStyle = "#0a1622"; ctx.fillRect(0, 0, w, h);
|
|
|
+ const top = 10, bottom = h - 25, plotH = bottom - top, threshold = Number($("threshold").value);
|
|
|
+ ctx.strokeStyle = "rgba(180,210,225,.18)"; ctx.lineWidth = 1;
|
|
|
+ for (let i = 0; i <= 4; i++) {
|
|
|
+ const y = bottom - i * plotH / 4;
|
|
|
+ ctx.beginPath(); ctx.moveTo(35, y); ctx.lineTo(w - 8, y); ctx.stroke();
|
|
|
+ ctx.fillStyle = "#8da4b3"; ctx.font = "10px Consolas"; ctx.fillText((i * .25).toFixed(2), 3, y + 3);
|
|
|
+ }
|
|
|
+ const x0 = 38, plotW = w - 48, step = plotW / state.windows.length;
|
|
|
+ const ty = bottom - threshold * plotH;
|
|
|
+ ctx.strokeStyle = "#ffca70"; ctx.setLineDash([6, 4]); ctx.beginPath(); ctx.moveTo(x0, ty); ctx.lineTo(w - 8, ty); ctx.stroke(); ctx.setLineDash([]);
|
|
|
+ state.windows.forEach((item, i) => {
|
|
|
+ const x = x0 + i * step + 1, bh = item.probability * plotH;
|
|
|
+ ctx.fillStyle = i === state.selectedWindow ? "#f4f7f9" : item.probability >= threshold ? "#ff725e" : "#65b8c6";
|
|
|
+ ctx.fillRect(x, bottom - bh, Math.max(2, step - 2), bh);
|
|
|
+ });
|
|
|
+ ctx.fillStyle = "#91a8b7"; ctx.font = "10px Consolas"; ctx.fillText("ВРЕМЯ →", w - 70, h - 6);
|
|
|
+ }
|
|
|
+
|
|
|
+ $("timeline").addEventListener("click", e => {
|
|
|
+ if (!state.windows.length) return;
|
|
|
+ const rect = e.currentTarget.getBoundingClientRect();
|
|
|
+ const x = (e.clientX - rect.left) / rect.width;
|
|
|
+ const index = Math.max(0, Math.min(state.windows.length - 1, Math.floor(x * state.windows.length)));
|
|
|
+ selectWindow(index);
|
|
|
+ });
|
|
|
+
|
|
|
+ // Initial placeholder chart and controls.
|
|
|
+ $("thresholdOut").textContent = Number($("threshold").value).toFixed(2);
|
|
|
+ $("spectrogram").getContext("2d").fillStyle = "#06101b";
|
|
|
+ $("spectrogram").getContext("2d").fillRect(0, 0, 704, 300);
|
|
|
+ $("decisionExplanation").textContent = "Выберите один из контрольных примеров или загрузите аудио/видео со звуком. Порог изменяет только правило принятия решения.";
|
|
|
+ window.GOLOS_DEBUG = { extractFeatures, predict, makeAudioSpectrogram };
|
|
|
+ // Built-in synchronized illustrative scenario (embedded video + staged dataset spectrograms).
|
|
|
+ const demoVideo = document.getElementById('demoVideo');
|
|
|
+ const demoStart = document.getElementById('demoStart');
|
|
|
+ const demoReset = document.getElementById('demoReset');
|
|
|
+ const demoAlert = document.getElementById('demoAlert');
|
|
|
+ let demoRunning = false, demoTick = null, demoLastSlot = -1;
|
|
|
+ const demoCandidates = SAMPLES.map(sample => {
|
|
|
+ const bytes = decodeBase64(sample.base64);
|
|
|
+ const result = predict(Float64Array.from(bytes, v => v * 0.3 - 45));
|
|
|
+ return {sample, bytes, result};
|
|
|
+ });
|
|
|
+ const demoBg = demoCandidates.filter(x => !x.sample.label).sort((a,b)=>a.result.probability-b.result.probability);
|
|
|
+ const demoUav = demoCandidates.filter(x => x.sample.label).sort((a,b)=>b.result.probability-a.result.probability);
|
|
|
+ function pickDemoSample(uav, index){
|
|
|
+ const list = uav ? demoUav : demoBg;
|
|
|
+ return list[index % Math.max(1,list.length)] || demoCandidates[0];
|
|
|
+ }
|
|
|
+ function demoSlot(time){ return Math.floor(time); }
|
|
|
+ function applyDemoSlot(slot){
|
|
|
+ if(slot===demoLastSlot)return; demoLastSlot=slot;
|
|
|
+ const event = slot>=6 && slot<13;
|
|
|
+ const item = pickDemoSample(event, event?slot-6:slot<6?slot:slot-13);
|
|
|
+ state.currentName = `СЦЕНАРИЙ · ${event?'БПЛА':'ФОН'} · ${slot+1}`;
|
|
|
+ state.spec = item.bytes; state.probability = item.result.probability; state.components = item.result.components;
|
|
|
+ state.truth = item.sample.label; state.windows = []; state.selectedWindow = 0;
|
|
|
+ drawSpectrogram(item.bytes); drawComponents(item.result.components); renderDecision();
|
|
|
+ $('specSource').textContent = `СЦЕНАРИЙ · ${slot+1}/18`;
|
|
|
+ $('featuresSource').textContent = 'ДЕМОНСТРАЦИОННЫЙ ПРОГОН';
|
|
|
+ $('analysisStatus').textContent = event ? 'СИГНАЛ В СЦЕНАРИИ' : 'ФОНОВОЕ НАБЛЮДЕНИЕ';
|
|
|
+ $('analysisStatus').className = `status-pill ${event?'alert':'ready'}`;
|
|
|
+ $('fileName').textContent = 'Встроенный сценарий синхронизирован с видеорядом';
|
|
|
+ $('decisionLabel').textContent = event ? 'СИГНАЛ БПЛА' : 'ФОН';
|
|
|
+ $('decisionLabel').className = `decision-label ${event?'detected':'background'}`;
|
|
|
+ demoAlert.classList.toggle('detected',event);
|
|
|
+ $('demoAlertText').textContent = event ? 'ТРЕВОГА · БПЛА' : 'НАБЛЮДЕНИЕ';
|
|
|
+ $('demoAlertSub').textContent = event ? 'В сценарии присутствует характерный сигнал' : 'Звуковой фон в пределах сценария';
|
|
|
+ $('demoCaption').textContent = event ? 'ОБНАРУЖЕН СИГНАЛ · РЕЖИМ ТРЕВОГИ' : slot>=13 ? 'СИГНАЛ УДАЛЯЕТСЯ · НАБЛЮДЕНИЕ' : 'ФОНОВАЯ ОБСТАНОВКА · НАБЛЮДЕНИЕ';
|
|
|
+ }
|
|
|
+ function demoFrame(){
|
|
|
+ if(!demoVideo || !demoRunning)return;
|
|
|
+ const t=Math.min(17.99,demoVideo.currentTime||0);
|
|
|
+ $('demoClock').textContent=`00:${String(Math.floor(t)).padStart(2,'0')}`;
|
|
|
+ applyDemoSlot(demoSlot(t));
|
|
|
+ if(t>=17.95){stopDemo();demoVideo.pause();demoVideo.currentTime=0;demoLastSlot=-1;applyDemoSlot(0);$('demoClock').textContent='00:00';}
|
|
|
+ }
|
|
|
+ function stopDemo(){demoRunning=false;clearInterval(demoTick);demoTick=null;demoStart.textContent='▶ ЗАПУСТИТЬ СЦЕНАРИЙ';}
|
|
|
+ demoStart?.addEventListener('click',async()=>{
|
|
|
+ if(demoRunning){stopDemo();demoVideo.pause();return;}
|
|
|
+ // stop the regular uploaded-file session to avoid confusing display state
|
|
|
+ demoRunning=true;demoStart.textContent='Ⅱ ПАУЗА';demoVideo.currentTime=0;demoLastSlot=-1;
|
|
|
+ try{await demoVideo.play();}catch(e){stopDemo();$('demoCaption').textContent='Не удалось запустить встроенный видеоряд';return;}
|
|
|
+ demoTick=setInterval(demoFrame,250);demoFrame();
|
|
|
+ });
|
|
|
+ demoReset?.addEventListener('click',()=>{stopDemo();demoVideo.pause();demoVideo.currentTime=0;demoLastSlot=-1;applyDemoSlot(0);$('demoClock').textContent='00:00';});
|
|
|
+ demoVideo?.addEventListener('ended',()=>{stopDemo();demoLastSlot=-1;applyDemoSlot(0);});
|
|
|
+ applyDemoSlot(0);
|
|
|
+
|
|
|
+})();
|
|
|
+
|