| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623 |
- (() => {
- "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 };
- // Embedded 40-second training scenario: audio + weather visuals + spectral display + manual scoring.
- const demoStart = $('demoStart'), demoReset = $('demoReset'), demoAlert = $('demoAlert');
- const demoAudio = $('demoAudio'), manualToggle = $('manualToggle');
- let demoRunning=false, demoTimer=null, demoSecond=-1, demoScoring=[];
- const scenarioDuration=40;
- const drone=$('droneSilhouette'), snow=$('snowLayer'), visual=$('demoVisual');
- // seconds 18..34: sound is present; the silhouette becomes visible only after 24 seconds.
- // a weak drone-like sound at 7..9 is a deliberately ambiguous background cue (false-alarm trap).
- function truthAt(t){return t>=18 && t<34;}
- function autoAt(t){return (t>=18 && t<34) || (t>=7 && t<9);}
- function autoConfidence(t){
- if(t>=18&&t<34){return t<20?.58:t<24?.76:t<30?.93:t<32?.78:.61;}
- if(t>=7&&t<9)return .69; // deliberately false positive
- return .12+((Math.sin(t*2.1)+1)*.025);
- }
- function renderDemoSpec(t){
- const bytes=new Uint8Array(64*44); const fade=(t>=18&&t<34)?Math.max(0,Math.min(1,(t-18)/4,(34-t)/4)):0;
- const falseCue=(t>=7&&t<9)?0.24:0;
- for(let f=0;f<64;f++)for(let x=0;x<44;x++){
- const noise=18+((Math.sin(f*3.2+x*1.7+t*5)+Math.cos(f*.8-x*2.1+t*3))*8)+((f*11+x*7)%17);
- const band=(f>=5&&f<=13)?12*Math.max(0,Math.sin(x*.8+t*2)):0;
- const harmonic=fade*(f===9||f===18||f===27||f===36?100:((f%9===0)?45:0)) + falseCue*((f%9===0)?38:0);
- const gust=(t<18||t>34)?22*Math.max(0,Math.sin(t*1.4+f*.5)):8;
- bytes[f*44+x]=Math.max(0,Math.min(255,Math.round(noise+band+harmonic+gust)));
- }
- return bytes;
- }
- function drawRollingSpec(t){
- const canvas=$('spectrogram'),ctx=canvas.getContext('2d');const W=canvas.width,H=canvas.height;
- ctx.fillStyle='#101d24';ctx.fillRect(0,0,W,H);
- const strip=renderDemoSpec(t),cw=W/44,ch=H/64;
- for(let f=0;f<64;f++)for(let x=0;x<44;x++){
- const v=strip[f*44+x],c=colorMap(v/255);
- ctx.fillStyle=`rgb(${c[0]},${c[1]},${c[2]})`;ctx.fillRect(x*cw,H-(f+1)*ch,Math.ceil(cw),Math.ceil(ch));
- }
- ctx.strokeStyle='rgba(230,215,185,.25)';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();}
- }
- function statsFor(which){
- let tp=0,fp=0,fn=0,tn=0;
- for(const row of demoScoring){const pred=which==='manual'?row.manual:row.auto; if(row.truth&&pred)tp++;else if(!row.truth&&pred)fp++;else if(row.truth&&!pred)fn++;else tn++;}
- return {tp,fp,fn,tn,score:Math.max(0,tp*10-fp*4-fn*6)};
- }
- function updateScoreboard(){
- const m=statsFor('manual'),a=statsFor('auto');
- $('manualScore').textContent=m.score; $('autoScore').textContent=a.score;
- $('manualStats').textContent=`TP ${m.tp} · FP ${m.fp} · FN ${m.fn}`;
- $('autoStats').textContent=`TP ${a.tp} · FP ${a.fp} · FN ${a.fn}`;
- }
- function evaluateSecond(t){
- if(t<0||t>=scenarioDuration)return;
- const manual=!!manualToggle.checked,truth=truthAt(t),auto=autoAt(t);
- demoScoring[t]={manual,truth,auto};updateScoreboard();
- }
- function updateDemo(t){
- const sec=Math.floor(t); if(sec===demoSecond)return;demoSecond=sec;
- const audible=truthAt(t),auto=autoAt(t),p=autoConfidence(t);
- drawRollingSpec(t);$('specSource').textContent=`СЦЕНАРИЙ · ${sec+1}/40`;
- $('demoClock').textContent=`00:${String(sec).padStart(2,'0')}`;
- $('demoCaption').textContent= t<14?'ФОНОВАЯ ОБСТАНОВКА · ВЕТЕР И ЛЁД':t<18?'СЛАБЫЙ АКУСТИЧЕСКИЙ СИГНАЛ · ОБЪЕКТ НЕ ВИДЕН':t<24?'СИГНАЛ ВИНТОВ · ОЖИДАНИЕ ВИЗУАЛЬНОГО ПОДТВЕРЖДЕНИЯ':t<30?'БПЛА В СЕКТОРЕ · СИГНАЛ ОТЧЁТЛИВ':t<34?'БПЛА УДАЛЯЕТСЯ · СИГНАЛ ЗАТУХАЕТ':'ФОН · СИГНАЛ ИСЧЕЗ';
- // Reveal the aircraft silhouette gradually after the alarm window begins.
- const vis=sec<24?0:sec<26?(sec-24)/2:sec<30?1:sec<32?(32-sec)/2:0;
- drone.style.opacity=Math.max(0,vis);drone.style.transform=`translate(${Math.max(0,sec-24)*4}px,${Math.max(0,sec-24)*1.8}px) scale(${.75+vis*.25})`;
- snow.style.opacity=(sec<14||sec>=34)?1:sec<18?.75:.35;
- const alarm=manualToggle.checked;
- demoAlert.classList.toggle('detected',alarm);$('demoAlertText').textContent=alarm?'РУЧНАЯ ТРЕВОГА':'НАБЛЮДЕНИЕ';
- $('demoAlertSub').textContent=alarm?'Оператор включил сигнал тревоги':'Фоновый шум / акустический контроль';
- $('manualState').textContent=alarm?'ТРЕВОГА ВКЛЮЧЕНА':'ТРЕВОГА ОТКЛЮЧЕНА';
- $('analysisStatus').textContent=auto?'АВТОМАТ: ОБНАРУЖЕНИЕ':'АВТОМАТ: ФОН';$('analysisStatus').className='status-pill '+(auto?'busy':'ready');
- $('scenarioStatus').textContent=`${sec.toString().padStart(2,'0')} / 40 С · ${audible?'ЗВУК БПЛА ПРИСУТСТВУЕТ':'ФОНОВАЯ ОБСТАНОВКА'} · АВТО ${Math.round(p*100)}%`;
- $('scenarioStatus').classList.toggle('scenario-alert',auto);
- // For scenario only, keep a clear and honest rule-based simulated automatic indicator, not an ML inference.
- $('decisionLabel').textContent=auto?'БПЛА / СИГНАЛ':'ФОН';$('decisionLabel').className='decision-label '+(auto?'drone':'');
- $('probText').textContent=`${Math.round(p*100)}%`;$('bgText').textContent=`${Math.round((1-p)*100)}%`;$('probBar').style.width=(p*100)+'%';$('bgBar').style.width=((1-p)*100)+'%';
- $('featuresSource').textContent='ВСТРОЕННЫЙ СЦЕНАРИЙ';$('specSource').textContent=`СЦЕНАРИЙ · ${sec+1}/40`;
- $('decisionExplanation').textContent='Автоматическая отметка в сценарии заранее размечена для учебного подсчёта; она не является выходом обученной ML-модели.';
- evaluateSecond(sec);
- }
- function stopDemo(){demoRunning=false;clearInterval(demoTimer);demoTimer=null;demoStart.textContent='▶ ЗАПУСК';demoAudio.pause();}
- function resetDemo(){stopDemo();demoAudio.currentTime=0;manualToggle.checked=false;demoScoring=[];demoSecond=-1;drone.style.opacity=0;updateScoreboard();drawRollingSpec(0);updateDemo(0);$('demoClock').textContent='00:00';$('scenarioStatus').textContent='СЦЕНАРИЙ ГОТОВ · ОЖИДАНИЕ';}
- demoStart?.addEventListener('click',async()=>{
- if(demoRunning){stopDemo();$('scenarioStatus').textContent='СЦЕНАРИЙ ПРИОСТАНОВЛЕН';return;}
- demoRunning=true;demoStart.textContent='Ⅱ ПАУЗА';demoSecond=-1;demoScoring=[];manualToggle.checked=false;demoAudio.currentTime=0;
- updateScoreboard();
- try{await demoAudio.play();}catch(e){stopDemo();$('scenarioStatus').textContent='Не удалось воспроизвести звук';return;}
- updateDemo(0);demoTimer=setInterval(()=>{const t=demoAudio.currentTime;updateDemo(t);if(t>=39.95){stopDemo();$('scenarioStatus').textContent='ИСПЫТАНИЕ ЗАВЕРШЕНО · СБРОС ДЛЯ ПОВТОРА';}},250);
- });
- demoReset?.addEventListener('click',resetDemo);
- manualToggle?.addEventListener('change',()=>{if(demoRunning){evaluateSecond(Math.floor(demoAudio.currentTime));updateDemo(demoAudio.currentTime);}});
- demoAudio?.addEventListener('ended',()=>{stopDemo();$('scenarioStatus').textContent='ИСПЫТАНИЕ ЗАВЕРШЕНО · СБРОС ДЛЯ ПОВТОРА';});
- resetDemo();
- })();
|