app.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. (() => {
  2. "use strict";
  3. const M = window.GOLOS_MODEL;
  4. const SAMPLES = window.GOLOS_SAMPLES || [];
  5. const $ = id => document.getElementById(id);
  6. const N_FREQ = 64, N_TIME = 44;
  7. const state = { probability: null, truth: null, components: null, spec: null, windows: [], selectedWindow: 0, objectUrl: null, currentName: "" };
  8. if (!M) {
  9. $("analysisStatus").textContent = "ОШИБКА: НЕТ МОДЕЛИ";
  10. throw new Error("model.js не загружен");
  11. }
  12. $("aucValue").textContent = Number(M.validation.rocAuc).toFixed(3);
  13. $("sampleButtons").innerHTML = "";
  14. SAMPLES.forEach(sample => {
  15. const b = document.createElement("button");
  16. b.type = "button";
  17. b.className = `sample-btn ${sample.label ? "uav" : "bg"}`;
  18. b.innerHTML = `${sample.name}<small>${sample.label ? "МЕТКА: БПЛА" : "МЕТКА: ФОН"}</small>`;
  19. b.addEventListener("click", () => {
  20. document.querySelectorAll(".sample-btn").forEach(x => x.classList.remove("active"));
  21. b.classList.add("active");
  22. const bytes = decodeBase64(sample.base64);
  23. const db = Float64Array.from(bytes, v => v * 0.3 - 45);
  24. const result = predict(db);
  25. state.currentName = sample.name;
  26. state.spec = bytes;
  27. state.truth = sample.label;
  28. state.windows = [];
  29. state.selectedWindow = 0;
  30. $("specSource").textContent = sample.name.toUpperCase();
  31. $("featuresSource").textContent = "ОБРАЗЕЦ ИЗ TRAIN.NPZ";
  32. $("timelineWrap").hidden = true;
  33. $("analysisStatus").textContent = "СПЕКТРОГРАММА ЗАГРУЖЕНА";
  34. $("analysisStatus").className = "status-pill ready";
  35. $("fileName").textContent = "Выбран встроенный образец обучающей выборки";
  36. if (!$("uploadedVideo").hidden) $("uploadedVideo").hidden = true;
  37. state.probability = result.probability;
  38. state.components = result.components;
  39. drawSpectrogram(bytes);
  40. drawComponents(result.components);
  41. renderDecision();
  42. });
  43. $("sampleButtons").appendChild(b);
  44. });
  45. $("threshold").addEventListener("input", () => {
  46. $("thresholdOut").textContent = Number($("threshold").value).toFixed(2);
  47. renderDecision();
  48. if (state.windows.length) drawTimeline();
  49. });
  50. $("mediaFile").addEventListener("change", async (event) => {
  51. const file = event.target.files && event.target.files[0];
  52. if (!file) return;
  53. await analyzeFile(file);
  54. });
  55. function decodeBase64(str) {
  56. const bin = atob(str);
  57. const a = new Uint8Array(bin.length);
  58. for (let i = 0; i < bin.length; i++) a[i] = bin.charCodeAt(i);
  59. return a;
  60. }
  61. function median(a) {
  62. const s = Array.from(a).sort((x, y) => x - y);
  63. const n = s.length;
  64. return n % 2 ? s[(n - 1) >> 1] : (s[n / 2 - 1] + s[n / 2]) / 2;
  65. }
  66. function mean(a) { let s = 0; for (const v of a) s += v; return s / a.length; }
  67. function std(a, m = mean(a)) {
  68. let s = 0; for (const v of a) { const d = v - m; s += d * d; }
  69. return Math.sqrt(s / a.length);
  70. }
  71. function corr(a, b) {
  72. if (a.length < 2) return 0;
  73. const ma = mean(a), mb = mean(b), sa = std(a, ma), sb = std(b, mb);
  74. const den = sa * sb;
  75. if (den < 1e-10) return 0;
  76. let s = 0; for (let i = 0; i < a.length; i++) s += (a[i] - ma) * (b[i] - mb);
  77. return (s / a.length) / den;
  78. }
  79. // Mirrors the 46-feature extraction in solution #2 of "ML1. Голос винта".
  80. function extractFeatures(S) {
  81. const P = new Float64Array(N_FREQ * N_TIME);
  82. const Pn = new Float64Array(N_FREQ * N_TIME);
  83. const cent = new Float64Array(N_TIME), bandwidth = new Float64Array(N_TIME);
  84. const flatness = new Float64Array(N_TIME), entropy = new Float64Array(N_TIME);
  85. const rolloff = new Float64Array(N_TIME), totalEnergy = new Float64Array(N_TIME);
  86. const freqIndex = new Float64Array(N_FREQ);
  87. for (let f = 0; f < N_FREQ; f++) freqIndex[f] = f;
  88. // MFCC: DCT-II over frequency for each time frame, after per-frame centering.
  89. const mfccMean = new Float64Array(13), mfccStd = new Float64Array(13);
  90. const mfccRows = Array.from({ length: 13 }, () => new Float64Array(N_TIME));
  91. const dctScale = new Float64Array(14);
  92. for (let k = 1; k <= 13; k++) dctScale[k] = Math.sqrt(2 / N_FREQ);
  93. for (let t = 0; t < N_TIME; t++) {
  94. let colMean = 0;
  95. for (let f = 0; f < N_FREQ; f++) colMean += S[f * N_TIME + t];
  96. colMean /= N_FREQ;
  97. for (let k = 1; k <= 13; k++) {
  98. let sum = 0;
  99. for (let f = 0; f < N_FREQ; f++) {
  100. sum += (S[f * N_TIME + t] - colMean) *
  101. Math.cos(Math.PI * (f + 0.5) * k / N_FREQ);
  102. }
  103. mfccRows[k - 1][t] = sum * dctScale[k];
  104. }
  105. }
  106. for (let k = 0; k < 13; k++) {
  107. mfccMean[k] = mean(mfccRows[k]);
  108. mfccStd[k] = std(mfccRows[k], mfccMean[k]);
  109. }
  110. const eps = 1e-10;
  111. let lowEnergy = 0, highEnergy = 0, sumAll = 0;
  112. for (let t = 0; t < N_TIME; t++) {
  113. let frameSum = 0;
  114. for (let f = 0; f < N_FREQ; f++) {
  115. const v = Math.pow(10, S[f * N_TIME + t] / 10);
  116. P[f * N_TIME + t] = v;
  117. frameSum += v;
  118. }
  119. frameSum += eps;
  120. totalEnergy[t] = frameSum - eps;
  121. sumAll += frameSum - eps;
  122. let c = 0, b = 0, logsum = 0, logsum2 = 0;
  123. for (let f = 0; f < N_FREQ; f++) {
  124. const ix = f * N_TIME + t;
  125. const pn = P[ix] / frameSum;
  126. Pn[ix] = pn;
  127. c += f * pn;
  128. const lp = Math.log(pn + eps);
  129. logsum += lp;
  130. logsum2 += pn * lp;
  131. if (f < 16) lowEnergy += P[ix];
  132. if (f >= 32) highEnergy += P[ix];
  133. }
  134. cent[t] = c;
  135. for (let f = 0; f < N_FREQ; f++) {
  136. const d = f - c; b += d * d * Pn[f * N_TIME + t];
  137. }
  138. bandwidth[t] = Math.sqrt(b);
  139. const gm = Math.exp(logsum / N_FREQ);
  140. const am = 1 / N_FREQ;
  141. flatness[t] = gm / (am + eps);
  142. entropy[t] = -logsum2 / Math.log(N_FREQ);
  143. let cumulative = 0, idx = 0;
  144. for (let f = 0; f < N_FREQ; f++) {
  145. cumulative += Pn[f * N_TIME + t];
  146. if (cumulative >= 0.85) { idx = f; break; }
  147. }
  148. rolloff[t] = idx / 63;
  149. }
  150. const ac1a = [], ac1b = [], ac2a = [], ac2b = [];
  151. const normalizedEnergy = Array.from(totalEnergy, v => v / (mean(totalEnergy) + eps));
  152. for (let t = 0; t < N_TIME - 1; t++) { ac1a.push(normalizedEnergy[t]); ac1b.push(normalizedEnergy[t + 1]); }
  153. for (let t = 0; t < N_TIME - 2; t++) { ac2a.push(normalizedEnergy[t]); ac2b.push(normalizedEnergy[t + 2]); }
  154. const ac1 = corr(ac1a, ac1b), ac2 = corr(ac2a, ac2b);
  155. const envMean = mean(normalizedEnergy);
  156. let zcrSum = 0, prevSign = Math.sign(normalizedEnergy[0] - envMean);
  157. for (let t = 1; t < N_TIME; t++) {
  158. const sign = Math.sign(normalizedEnergy[t] - envMean);
  159. zcrSum += Math.abs(sign - prevSign);
  160. prevSign = sign;
  161. }
  162. const zcr = zcrSum / (2 * (N_TIME - 1));
  163. const total = sumAll + eps;
  164. const lowRatio = lowEnergy / total, highRatio = highEnergy / total;
  165. const rowStats = [];
  166. const flatSn = new Float64Array(N_FREQ * N_TIME);
  167. for (let f = 0; f < N_FREQ; f++) {
  168. const row = new Float64Array(N_TIME);
  169. for (let t = 0; t < N_TIME; t++) row[t] = S[f * N_TIME + t];
  170. const med = median(row);
  171. for (let t = 0; t < N_TIME; t++) flatSn[f * N_TIME + t] = row[t] - med;
  172. rowStats.push(row);
  173. }
  174. let m = 0;
  175. for (const v of flatSn) m += v;
  176. m /= flatSn.length;
  177. const s = std(flatSn);
  178. let m3 = 0, m4 = 0;
  179. for (const v of flatSn) {
  180. const d = v - m; m3 += d ** 3; m4 += d ** 4;
  181. }
  182. m3 /= flatSn.length; m4 /= flatSn.length;
  183. const kurt = m4 / (s ** 4 + eps) - 3;
  184. const skew = m3 / (s ** 3 + eps);
  185. const freqVar = new Float64Array(N_FREQ), freqRange = new Float64Array(N_FREQ);
  186. for (let f = 0; f < N_FREQ; f++) {
  187. let sm = 0, mn = Infinity, mx = -Infinity;
  188. for (let t = 0; t < N_TIME; t++) {
  189. const v = flatSn[f * N_TIME + t];
  190. sm += v; if (v < mn) mn = v; if (v > mx) mx = v;
  191. }
  192. const rm = sm / N_TIME;
  193. let vv = 0;
  194. for (let t = 0; t < N_TIME; t++) {
  195. const d = flatSn[f * N_TIME + t] - rm; vv += d * d;
  196. }
  197. freqVar[f] = vv / N_TIME;
  198. freqRange[f] = mx - mn;
  199. }
  200. const f = [
  201. ...mfccMean, ...mfccStd,
  202. mean(cent), std(cent),
  203. mean(bandwidth), std(bandwidth),
  204. mean(rolloff),
  205. mean(flatness), std(flatness),
  206. mean(entropy), std(entropy),
  207. ac1, ac2, zcr,
  208. lowRatio, highRatio,
  209. kurt, skew,
  210. mean(freqVar), std(freqVar),
  211. mean(freqRange), std(freqRange)
  212. ];
  213. return f;
  214. }
  215. function predict(dbArray) {
  216. const raw = extractFeatures(dbArray);
  217. const norm = raw.map((v, i) => (v - M.rawMean[i]) / M.rawStd[i]);
  218. const pcs = new Array(16);
  219. for (let k = 0; k < 16; k++) {
  220. let sum = 0;
  221. for (let j = 0; j < norm.length; j++) sum += norm[j] * M.components[k][j];
  222. pcs[k] = (sum - M.projectionMean[k]) / M.projectionStd[k];
  223. }
  224. let z = M.intercept;
  225. for (let k = 0; k < 16; k++) z += pcs[k] * M.coef[k];
  226. const p = 1 / (1 + Math.exp(-Math.max(-40, Math.min(40, z))));
  227. return { probability: p, components: pcs, raw };
  228. }
  229. function colorMap(v) {
  230. const stops = [
  231. [0.00, [3, 13, 38]], [0.20, [0, 54, 110]], [0.40, [0, 154, 174]],
  232. [0.60, [76, 205, 151]], [0.78, [246, 218, 72]], [0.90, [246, 111, 43]], [1.00, [245, 42, 55]]
  233. ];
  234. let a = stops[0], b = stops[stops.length - 1];
  235. for (let i = 0; i < stops.length - 1; i++) {
  236. if (v >= stops[i][0] && v <= stops[i + 1][0]) { a = stops[i]; b = stops[i + 1]; break; }
  237. }
  238. const t = (v - a[0]) / (b[0] - a[0] || 1);
  239. return a[1].map((c, i) => Math.round(c + (b[1][i] - c) * t));
  240. }
  241. function drawSpectrogram(bytes) {
  242. const canvas = $("spectrogram"), ctx = canvas.getContext("2d");
  243. const w = canvas.width, h = canvas.height;
  244. ctx.fillStyle = "#06101b"; ctx.fillRect(0, 0, w, h);
  245. let mn = 255, mx = 0;
  246. for (const v of bytes) { if (v < mn) mn = v; if (v > mx) mx = v; }
  247. const range = Math.max(1, mx - mn);
  248. const cellW = w / N_TIME, cellH = h / N_FREQ;
  249. for (let f = 0; f < N_FREQ; f++) {
  250. for (let t = 0; t < N_TIME; t++) {
  251. const v = bytes[f * N_TIME + t];
  252. const c = colorMap((v - mn) / range);
  253. ctx.fillStyle = `rgb(${c[0]},${c[1]},${c[2]})`;
  254. ctx.fillRect(t * cellW, h - (f + 1) * cellH, Math.ceil(cellW + .3), Math.ceil(cellH + .3));
  255. }
  256. }
  257. ctx.strokeStyle = "rgba(205,235,245,.14)"; ctx.lineWidth = 1;
  258. for (let i = 1; i < 4; i++) { ctx.beginPath(); ctx.moveTo(0, h * i / 4); ctx.lineTo(w, h * i / 4); ctx.stroke(); }
  259. for (let i = 1; i < 4; i++) { ctx.beginPath(); ctx.moveTo(w * i / 4, 0); ctx.lineTo(w * i / 4, h); ctx.stroke(); }
  260. }
  261. function drawComponents(pcs) {
  262. const root = $("componentBars"); root.innerHTML = "";
  263. const max = Math.max(0.1, ...pcs.map(Math.abs));
  264. pcs.forEach((value, i) => {
  265. const el = document.createElement("div"); el.className = "comp";
  266. const pct = Math.max(2, Math.round(Math.abs(value) / max * 100));
  267. 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>`;
  268. root.appendChild(el);
  269. });
  270. }
  271. function renderDecision() {
  272. const threshold = Number($("threshold").value);
  273. const p = state.probability;
  274. $("thresholdOut").textContent = threshold.toFixed(2);
  275. if (p == null) return;
  276. const positive = p >= threshold;
  277. $("decisionLabel").textContent = positive ? "БПЛА ОБНАРУЖЕН" : "ФОН";
  278. $("decisionLabel").className = "decision-label" + (positive ? " drone" : "");
  279. $("probText").textContent = (p * 100).toFixed(1) + "%";
  280. $("bgText").textContent = ((1 - p) * 100).toFixed(1) + "%";
  281. $("probBar").style.width = (p * 100) + "%";
  282. $("bgBar").style.width = ((1 - p) * 100) + "%";
  283. const explanation = positive
  284. ? "Оценка класса БПЛА достигла порога. Система формирует отметку обнаружения."
  285. : "Оценка класса БПЛА ниже порога. Система относит запись к фоновому классу.";
  286. $("decisionExplanation").textContent = explanation + " Измените порог и наблюдайте, как меняется решение.";
  287. const truth = $("truthBadge");
  288. if (state.truth != null) {
  289. truth.hidden = false;
  290. const correct = (positive ? 1 : 0) === state.truth;
  291. truth.className = "truth-badge " + (correct ? "good" : "bad");
  292. truth.textContent = `Исходная метка: ${state.truth ? "БПЛА" : "ФОН"} · ${correct ? "Решение совпало с меткой" : "Решение не совпало с меткой"}`;
  293. } else {
  294. truth.hidden = true;
  295. }
  296. }
  297. function resampleLinear(src, sourceRate, targetRate) {
  298. if (sourceRate === targetRate) return src;
  299. const len = Math.max(1, Math.floor(src.length * targetRate / sourceRate));
  300. const dst = new Float32Array(len);
  301. const ratio = sourceRate / targetRate;
  302. for (let i = 0; i < len; i++) {
  303. const pos = i * ratio, left = Math.floor(pos), frac = pos - left;
  304. const a = src[Math.min(left, src.length - 1)];
  305. const b = src[Math.min(left + 1, src.length - 1)];
  306. dst[i] = a + (b - a) * frac;
  307. }
  308. return dst;
  309. }
  310. function fft(re, im) {
  311. const n = re.length;
  312. let j = 0;
  313. for (let i = 1; i < n; i++) {
  314. let bit = n >> 1;
  315. while (j & bit) { j ^= bit; bit >>= 1; }
  316. j ^= bit;
  317. if (i < j) {
  318. [re[i], re[j]] = [re[j], re[i]];
  319. [im[i], im[j]] = [im[j], im[i]];
  320. }
  321. }
  322. for (let len = 2; len <= n; len <<= 1) {
  323. const angle = -2 * Math.PI / len;
  324. const wlenR = Math.cos(angle), wlenI = Math.sin(angle);
  325. for (let i = 0; i < n; i += len) {
  326. let wr = 1, wi = 0;
  327. for (let k = 0; k < len / 2; k++) {
  328. const uR = re[i + k], uI = im[i + k];
  329. const vR = re[i + k + len / 2] * wr - im[i + k + len / 2] * wi;
  330. const vI = re[i + k + len / 2] * wi + im[i + k + len / 2] * wr;
  331. re[i + k] = uR + vR; im[i + k] = uI + vI;
  332. re[i + k + len / 2] = uR - vR; im[i + k + len / 2] = uI - vI;
  333. const nextWr = wr * wlenR - wi * wlenI;
  334. wi = wr * wlenI + wi * wlenR; wr = nextWr;
  335. }
  336. }
  337. }
  338. }
  339. const melBank = (() => {
  340. const sr = 16000, nfft = 1024, bins = nfft / 2 + 1, filters = [];
  341. const hzToMel = hz => 2595 * Math.log10(1 + hz / 700);
  342. const melToHz = mel => 700 * (Math.pow(10, mel / 2595) - 1);
  343. const low = hzToMel(30), high = hzToMel(8000);
  344. const edges = Array.from({ length: 66 }, (_, i) => melToHz(low + (high - low) * i / 65));
  345. for (let m = 0; m < 64; m++) {
  346. const row = new Float64Array(bins);
  347. const a = edges[m], b = edges[m + 1], c = edges[m + 2];
  348. let first = bins, last = 0;
  349. for (let k = 0; k < bins; k++) {
  350. const f = k * sr / nfft;
  351. row[k] = f < a || f > c ? 0 : f <= b ? (f - a) / (b - a) : (c - f) / (c - b);
  352. if (row[k] > 0) { first = Math.min(first, k); last = k; }
  353. }
  354. filters.push({ weights: row, first, last });
  355. }
  356. return filters;
  357. })();
  358. function makeAudioSpectrogram(audio, startSample) {
  359. const sr = 16000, nfft = 1024, frameCount = 44, need = sr;
  360. const segment = new Float32Array(need);
  361. for (let i = 0; i < need; i++) segment[i] = audio[startSample + i] || 0;
  362. const energies = new Float64Array(64 * frameCount);
  363. const starts = Array.from({ length: frameCount }, (_, i) => Math.round(i * (need - nfft) / (frameCount - 1)));
  364. const hann = new Float64Array(nfft);
  365. for (let i = 0; i < nfft; i++) hann[i] = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / (nfft - 1));
  366. let globalMax = 1e-15;
  367. for (let t = 0; t < frameCount; t++) {
  368. const re = new Float64Array(nfft), im = new Float64Array(nfft);
  369. const start = starts[t];
  370. for (let i = 0; i < nfft; i++) re[i] = segment[start + i] * hann[i];
  371. fft(re, im);
  372. const power = new Float64Array(nfft / 2 + 1);
  373. for (let k = 0; k < power.length; k++) power[k] = (re[k] * re[k] + im[k] * im[k]) / (nfft * nfft);
  374. for (let f = 0; f < 64; f++) {
  375. let e = 0; const filter = melBank[f];
  376. for (let k = filter.first; k <= filter.last; k++) e += power[k] * filter.weights[k];
  377. energies[f * frameCount + t] = e;
  378. if (e > globalMax) globalMax = e;
  379. }
  380. }
  381. const bytes = new Uint8Array(64 * 44);
  382. for (let i = 0; i < energies.length; i++) {
  383. let db = 10 * Math.log10(Math.max(energies[i], 1e-15) / globalMax);
  384. db = Math.max(-45, Math.min(31.5, db));
  385. bytes[i] = Math.max(0, Math.min(255, Math.round((db + 45) / 0.3)));
  386. }
  387. return bytes;
  388. }
  389. async function analyzeFile(file) {
  390. $("analysisStatus").textContent = "ОБРАБОТКА...";
  391. $("analysisStatus").className = "status-pill busy";
  392. $("fileName").textContent = file.name;
  393. $("truthBadge").hidden = true;
  394. $("timelineWrap").hidden = true;
  395. state.truth = null; state.windows = [];
  396. const vid = $("uploadedVideo");
  397. if (state.objectUrl) URL.revokeObjectURL(state.objectUrl);
  398. state.objectUrl = URL.createObjectURL(file);
  399. if (file.type.startsWith("video/")) {
  400. vid.src = state.objectUrl; vid.hidden = false;
  401. } else {
  402. vid.hidden = true; vid.removeAttribute("src");
  403. }
  404. try {
  405. const AudioCtx = window.AudioContext || window.webkitAudioContext;
  406. if (!AudioCtx) throw new Error("Браузер не поддерживает Web Audio API.");
  407. const audioCtx = new AudioCtx();
  408. const bytes = await file.arrayBuffer();
  409. let buffer;
  410. try { buffer = await audioCtx.decodeAudioData(bytes.slice(0)); }
  411. catch { await audioCtx.close(); throw new Error("Не удалось прочитать звуковую дорожку. Попробуйте WAV, MP3 или отдельный аудиофайл, извлечённый из видео."); }
  412. const length = buffer.length;
  413. const mono = new Float32Array(length);
  414. for (let ch = 0; ch < buffer.numberOfChannels; ch++) {
  415. const data = buffer.getChannelData(ch);
  416. for (let i = 0; i < length; i++) mono[i] += data[i] / buffer.numberOfChannels;
  417. }
  418. const audio = resampleLinear(mono, buffer.sampleRate, 16000);
  419. await audioCtx.close();
  420. if (audio.length < 4000) throw new Error("В файле слишком короткая звуковая дорожка.");
  421. const duration = audio.length / 16000;
  422. const hop = 0.5, count = Math.min(80, Math.max(1, Math.floor((duration - 1) / hop) + 1));
  423. const windows = [];
  424. for (let i = 0; i < count; i++) {
  425. const start = Math.round(i * hop * 16000);
  426. const bytesSpec = makeAudioSpectrogram(audio, start);
  427. const db = Float64Array.from(bytesSpec, v => v * 0.3 - 45);
  428. const result = predict(db);
  429. windows.push({ start: i * hop, probability: result.probability, spec: bytesSpec, components: result.components });
  430. if (i % 4 === 3) await new Promise(resolve => setTimeout(resolve, 0));
  431. }
  432. state.windows = windows;
  433. const bestIndex = windows.reduce((best, w, i) => w.probability > windows[best].probability ? i : best, 0);
  434. state.selectedWindow = bestIndex;
  435. selectWindow(bestIndex);
  436. $("timelineWrap").hidden = windows.length < 2;
  437. $("timelineLabel").textContent = `${windows.length} окон · шаг 0,5 с · длительность ${duration.toFixed(1)} с`;
  438. drawTimeline();
  439. $("analysisStatus").textContent = "АНАЛИЗ ЗАВЕРШЁН";
  440. $("analysisStatus").className = "status-pill ready";
  441. } catch (err) {
  442. $("analysisStatus").textContent = "ОШИБКА ЧТЕНИЯ";
  443. $("analysisStatus").className = "status-pill";
  444. $("decisionLabel").textContent = "НЕТ РЕЗУЛЬТАТА";
  445. $("decisionLabel").className = "decision-label empty";
  446. $("decisionExplanation").textContent = err && err.message ? err.message : "Не удалось обработать запись.";
  447. $("probText").textContent = $("bgText").textContent = "—";
  448. $("probBar").style.width = $("bgBar").style.width = "0%";
  449. $("spectrogram").getContext("2d").clearRect(0, 0, 704, 300);
  450. $("componentBars").innerHTML = '<div class="empty-features">Нет данных для отображения.</div>';
  451. state.probability = null;
  452. }
  453. }
  454. function selectWindow(index) {
  455. const w = state.windows[index];
  456. if (!w) return;
  457. state.selectedWindow = index;
  458. state.probability = w.probability;
  459. state.truth = null;
  460. state.spec = w.spec;
  461. state.components = w.components;
  462. $("specSource").textContent = `ФРАГМЕНТ ${index + 1} · ${w.start.toFixed(1)} С`;
  463. $("featuresSource").textContent = `ОКНО ${index + 1}/${state.windows.length}`;
  464. drawSpectrogram(w.spec);
  465. drawComponents(w.components);
  466. renderDecision();
  467. if (state.windows.length) drawTimeline();
  468. }
  469. function drawTimeline() {
  470. const canvas = $("timeline"), ctx = canvas.getContext("2d");
  471. const w = canvas.width, h = canvas.height;
  472. ctx.fillStyle = "#0a1622"; ctx.fillRect(0, 0, w, h);
  473. const top = 10, bottom = h - 25, plotH = bottom - top, threshold = Number($("threshold").value);
  474. ctx.strokeStyle = "rgba(180,210,225,.18)"; ctx.lineWidth = 1;
  475. for (let i = 0; i <= 4; i++) {
  476. const y = bottom - i * plotH / 4;
  477. ctx.beginPath(); ctx.moveTo(35, y); ctx.lineTo(w - 8, y); ctx.stroke();
  478. ctx.fillStyle = "#8da4b3"; ctx.font = "10px Consolas"; ctx.fillText((i * .25).toFixed(2), 3, y + 3);
  479. }
  480. const x0 = 38, plotW = w - 48, step = plotW / state.windows.length;
  481. const ty = bottom - threshold * plotH;
  482. ctx.strokeStyle = "#ffca70"; ctx.setLineDash([6, 4]); ctx.beginPath(); ctx.moveTo(x0, ty); ctx.lineTo(w - 8, ty); ctx.stroke(); ctx.setLineDash([]);
  483. state.windows.forEach((item, i) => {
  484. const x = x0 + i * step + 1, bh = item.probability * plotH;
  485. ctx.fillStyle = i === state.selectedWindow ? "#f4f7f9" : item.probability >= threshold ? "#ff725e" : "#65b8c6";
  486. ctx.fillRect(x, bottom - bh, Math.max(2, step - 2), bh);
  487. });
  488. ctx.fillStyle = "#91a8b7"; ctx.font = "10px Consolas"; ctx.fillText("ВРЕМЯ →", w - 70, h - 6);
  489. }
  490. $("timeline").addEventListener("click", e => {
  491. if (!state.windows.length) return;
  492. const rect = e.currentTarget.getBoundingClientRect();
  493. const x = (e.clientX - rect.left) / rect.width;
  494. const index = Math.max(0, Math.min(state.windows.length - 1, Math.floor(x * state.windows.length)));
  495. selectWindow(index);
  496. });
  497. // Initial placeholder chart and controls.
  498. $("thresholdOut").textContent = Number($("threshold").value).toFixed(2);
  499. $("spectrogram").getContext("2d").fillStyle = "#06101b";
  500. $("spectrogram").getContext("2d").fillRect(0, 0, 704, 300);
  501. $("decisionExplanation").textContent = "Выберите один из контрольных примеров или загрузите аудио/видео со звуком. Порог изменяет только правило принятия решения.";
  502. window.GOLOS_DEBUG = { extractFeatures, predict, makeAudioSpectrogram };
  503. // Embedded 40-second training scenario: audio + weather visuals + spectral display + manual scoring.
  504. const demoStart = $('demoStart'), demoReset = $('demoReset'), demoAlert = $('demoAlert');
  505. const demoAudio = $('demoAudio'), manualToggle = $('manualToggle');
  506. let demoRunning=false, demoTimer=null, demoSecond=-1, demoScoring=[];
  507. const scenarioDuration=40;
  508. const drone=$('droneSilhouette'), snow=$('snowLayer'), visual=$('demoVisual');
  509. // seconds 18..34: sound is present; the silhouette becomes visible only after 24 seconds.
  510. // a weak drone-like sound at 7..9 is a deliberately ambiguous background cue (false-alarm trap).
  511. function truthAt(t){return t>=18 && t<34;}
  512. function autoAt(t){return (t>=18 && t<34) || (t>=7 && t<9);}
  513. function autoConfidence(t){
  514. if(t>=18&&t<34){return t<20?.58:t<24?.76:t<30?.93:t<32?.78:.61;}
  515. if(t>=7&&t<9)return .69; // deliberately false positive
  516. return .12+((Math.sin(t*2.1)+1)*.025);
  517. }
  518. function renderDemoSpec(t){
  519. 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;
  520. const falseCue=(t>=7&&t<9)?0.24:0;
  521. for(let f=0;f<64;f++)for(let x=0;x<44;x++){
  522. 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);
  523. const band=(f>=5&&f<=13)?12*Math.max(0,Math.sin(x*.8+t*2)):0;
  524. const harmonic=fade*(f===9||f===18||f===27||f===36?100:((f%9===0)?45:0)) + falseCue*((f%9===0)?38:0);
  525. const gust=(t<18||t>34)?22*Math.max(0,Math.sin(t*1.4+f*.5)):8;
  526. bytes[f*44+x]=Math.max(0,Math.min(255,Math.round(noise+band+harmonic+gust)));
  527. }
  528. return bytes;
  529. }
  530. function drawRollingSpec(t){
  531. const canvas=$('spectrogram'),ctx=canvas.getContext('2d');const W=canvas.width,H=canvas.height;
  532. ctx.fillStyle='#101d24';ctx.fillRect(0,0,W,H);
  533. const strip=renderDemoSpec(t),cw=W/44,ch=H/64;
  534. for(let f=0;f<64;f++)for(let x=0;x<44;x++){
  535. const v=strip[f*44+x],c=colorMap(v/255);
  536. ctx.fillStyle=`rgb(${c[0]},${c[1]},${c[2]})`;ctx.fillRect(x*cw,H-(f+1)*ch,Math.ceil(cw),Math.ceil(ch));
  537. }
  538. ctx.strokeStyle='rgba(230,215,185,.25)';ctx.lineWidth=1;
  539. for(let i=1;i<4;i++){ctx.beginPath();ctx.moveTo(0,H*i/4);ctx.lineTo(W,H*i/4);ctx.stroke();}
  540. }
  541. function statsFor(which){
  542. let tp=0,fp=0,fn=0,tn=0;
  543. 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++;}
  544. return {tp,fp,fn,tn,score:Math.max(0,tp*10-fp*4-fn*6)};
  545. }
  546. function updateScoreboard(){
  547. const m=statsFor('manual'),a=statsFor('auto');
  548. $('manualScore').textContent=m.score; $('autoScore').textContent=a.score;
  549. $('manualStats').textContent=`TP ${m.tp} · FP ${m.fp} · FN ${m.fn}`;
  550. $('autoStats').textContent=`TP ${a.tp} · FP ${a.fp} · FN ${a.fn}`;
  551. }
  552. function evaluateSecond(t){
  553. if(t<0||t>=scenarioDuration)return;
  554. const manual=!!manualToggle.checked,truth=truthAt(t),auto=autoAt(t);
  555. demoScoring[t]={manual,truth,auto};updateScoreboard();
  556. }
  557. function updateDemo(t){
  558. const sec=Math.floor(t); if(sec===demoSecond)return;demoSecond=sec;
  559. const audible=truthAt(t),auto=autoAt(t),p=autoConfidence(t);
  560. drawRollingSpec(t);$('specSource').textContent=`СЦЕНАРИЙ · ${sec+1}/40`;
  561. $('demoClock').textContent=`00:${String(sec).padStart(2,'0')}`;
  562. $('demoCaption').textContent= t<14?'ФОНОВАЯ ОБСТАНОВКА · ВЕТЕР И ЛЁД':t<18?'СЛАБЫЙ АКУСТИЧЕСКИЙ СИГНАЛ · ОБЪЕКТ НЕ ВИДЕН':t<24?'СИГНАЛ ВИНТОВ · ОЖИДАНИЕ ВИЗУАЛЬНОГО ПОДТВЕРЖДЕНИЯ':t<30?'БПЛА В СЕКТОРЕ · СИГНАЛ ОТЧЁТЛИВ':t<34?'БПЛА УДАЛЯЕТСЯ · СИГНАЛ ЗАТУХАЕТ':'ФОН · СИГНАЛ ИСЧЕЗ';
  563. // Reveal the aircraft silhouette gradually after the alarm window begins.
  564. const vis=sec<24?0:sec<26?(sec-24)/2:sec<30?1:sec<32?(32-sec)/2:0;
  565. 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})`;
  566. snow.style.opacity=(sec<14||sec>=34)?1:sec<18?.75:.35;
  567. const alarm=manualToggle.checked;
  568. demoAlert.classList.toggle('detected',alarm);$('demoAlertText').textContent=alarm?'РУЧНАЯ ТРЕВОГА':'НАБЛЮДЕНИЕ';
  569. $('demoAlertSub').textContent=alarm?'Оператор включил сигнал тревоги':'Фоновый шум / акустический контроль';
  570. $('manualState').textContent=alarm?'ТРЕВОГА ВКЛЮЧЕНА':'ТРЕВОГА ОТКЛЮЧЕНА';
  571. $('analysisStatus').textContent=auto?'АВТОМАТ: ОБНАРУЖЕНИЕ':'АВТОМАТ: ФОН';$('analysisStatus').className='status-pill '+(auto?'busy':'ready');
  572. $('scenarioStatus').textContent=`${sec.toString().padStart(2,'0')} / 40 С · ${audible?'ЗВУК БПЛА ПРИСУТСТВУЕТ':'ФОНОВАЯ ОБСТАНОВКА'} · АВТО ${Math.round(p*100)}%`;
  573. $('scenarioStatus').classList.toggle('scenario-alert',auto);
  574. // For scenario only, keep a clear and honest rule-based simulated automatic indicator, not an ML inference.
  575. $('decisionLabel').textContent=auto?'БПЛА / СИГНАЛ':'ФОН';$('decisionLabel').className='decision-label '+(auto?'drone':'');
  576. $('probText').textContent=`${Math.round(p*100)}%`;$('bgText').textContent=`${Math.round((1-p)*100)}%`;$('probBar').style.width=(p*100)+'%';$('bgBar').style.width=((1-p)*100)+'%';
  577. $('featuresSource').textContent='ВСТРОЕННЫЙ СЦЕНАРИЙ';$('specSource').textContent=`СЦЕНАРИЙ · ${sec+1}/40`;
  578. $('decisionExplanation').textContent='Автоматическая отметка в сценарии заранее размечена для учебного подсчёта; она не является выходом обученной ML-модели.';
  579. evaluateSecond(sec);
  580. }
  581. function stopDemo(){demoRunning=false;clearInterval(demoTimer);demoTimer=null;demoStart.textContent='▶ ЗАПУСК';demoAudio.pause();}
  582. 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='СЦЕНАРИЙ ГОТОВ · ОЖИДАНИЕ';}
  583. demoStart?.addEventListener('click',async()=>{
  584. if(demoRunning){stopDemo();$('scenarioStatus').textContent='СЦЕНАРИЙ ПРИОСТАНОВЛЕН';return;}
  585. demoRunning=true;demoStart.textContent='Ⅱ ПАУЗА';demoSecond=-1;demoScoring=[];manualToggle.checked=false;demoAudio.currentTime=0;
  586. updateScoreboard();
  587. try{await demoAudio.play();}catch(e){stopDemo();$('scenarioStatus').textContent='Не удалось воспроизвести звук';return;}
  588. updateDemo(0);demoTimer=setInterval(()=>{const t=demoAudio.currentTime;updateDemo(t);if(t>=39.95){stopDemo();$('scenarioStatus').textContent='ИСПЫТАНИЕ ЗАВЕРШЕНО · СБРОС ДЛЯ ПОВТОРА';}},250);
  589. });
  590. demoReset?.addEventListener('click',resetDemo);
  591. manualToggle?.addEventListener('change',()=>{if(demoRunning){evaluateSecond(Math.floor(demoAudio.currentTime));updateDemo(demoAudio.currentTime);}});
  592. demoAudio?.addEventListener('ended',()=>{stopDemo();$('scenarioStatus').textContent='ИСПЫТАНИЕ ЗАВЕРШЕНО · СБРОС ДЛЯ ПОВТОРА';});
  593. resetDemo();
  594. })();