@hyperwindmill/caretaker-cli 0.30.0 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/web/voice_backend.d.ts +4 -0
- package/dist/cli/web/voice_backend.d.ts.map +1 -1
- package/dist/cli/web/voice_backend.js +14 -3
- package/dist/cli/web/voice_builtin.d.ts.map +1 -1
- package/dist/cli/web/voice_builtin.js +32 -13
- package/dist/cli/web/voice_proxy.d.ts +3 -0
- package/dist/cli/web/voice_proxy.d.ts.map +1 -1
- package/dist/cli/web/voice_proxy.js +28 -3
- package/dist/harness/tools/builtin/set_workspace.d.ts.map +1 -1
- package/dist/harness/tools/builtin/set_workspace.js +26 -4
- package/dist/session/store.d.ts +2 -2
- package/dist/session/store.d.ts.map +1 -1
- package/dist/session/store.js +5 -2
- package/dist/session/types.d.ts +2 -1
- package/dist/session/types.d.ts.map +1 -1
- package/dist/store/db.d.ts.map +1 -1
- package/dist/store/db.js +3 -1
- package/dist/voice/pocket/install.d.ts +16 -2
- package/dist/voice/pocket/install.d.ts.map +1 -1
- package/dist/voice/pocket/install.js +59 -5
- package/dist/voice/pronunciation.d.ts.map +1 -1
- package/dist/voice/pronunciation.js +3 -0
- package/dist/voice/whisper/catalog.d.ts +15 -0
- package/dist/voice/whisper/catalog.d.ts.map +1 -0
- package/dist/voice/whisper/catalog.js +53 -0
- package/dist/voice/whisper/decoder.d.ts +3 -0
- package/dist/voice/whisper/decoder.d.ts.map +1 -0
- package/dist/voice/whisper/decoder.js +48 -0
- package/dist/voice/whisper/engine.d.ts +8 -0
- package/dist/voice/whisper/engine.d.ts.map +1 -0
- package/dist/voice/whisper/engine.js +77 -0
- package/dist/voice/whisper/features.d.ts +10 -0
- package/dist/voice/whisper/features.d.ts.map +1 -0
- package/dist/voice/whisper/features.js +149 -0
- package/dist/voice/whisper/inference.d.ts +17 -0
- package/dist/voice/whisper/inference.d.ts.map +1 -0
- package/dist/voice/whisper/inference.js +257 -0
- package/dist/voice/whisper/wav.d.ts +5 -0
- package/dist/voice/whisper/wav.d.ts.map +1 -0
- package/dist/voice/whisper/wav.js +48 -0
- package/dist/webview/standalone.js +914 -687
- package/dist/webview/standalone.js.map +4 -4
- package/package.json +3 -3
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Pinned catalog for the built-in Whisper transcription engine: ONNX exports on Hugging Face.
|
|
2
|
+
//
|
|
3
|
+
// Weights: OpenAI Whisper, MIT licence. ONNX export: onnx-community (transformers.js
|
|
4
|
+
// layout). Each size is pinned to one commit, with sha256 and size per file; the two
|
|
5
|
+
// graphs are the quantized encoder and the q4 merged decoder (the int8 decoder was
|
|
6
|
+
// measured 2.5x slower per token on a CPU without VNNI). `name` keeps the repo path;
|
|
7
|
+
// the installer decides how to lay the files out on disk.
|
|
8
|
+
// Files live at <base>/onnx-community/whisper-<size>/resolve/<revision>/<name>.
|
|
9
|
+
export const WHISPER_BASE_URL = 'https://huggingface.co';
|
|
10
|
+
export const WHISPER_MODELS = {
|
|
11
|
+
tiny: {
|
|
12
|
+
repo: 'onnx-community/whisper-tiny',
|
|
13
|
+
revision: 'ff4177021cc41f7db950912b73ea4fdf7d01d8e7',
|
|
14
|
+
files: [
|
|
15
|
+
{ name: 'onnx/encoder_model_quantized.onnx', sha256: '2af4a414ca47aa30f61246017e5fe82b0a8d229281d1255ba666a2a7f6b84d19', bytes: 10124990 },
|
|
16
|
+
{ name: 'onnx/decoder_model_merged_q4.onnx', sha256: 'a7573efde84f7d018d59e50e7f860c03e26623d68e23eb6037b76135367e72eb', bytes: 86713702 },
|
|
17
|
+
{ name: 'vocab.json', sha256: '50d6a919f0a0601d56a04eb583c780d18553aa388254ba3158eb6a00f13e2c1a', bytes: 1036584 },
|
|
18
|
+
{ name: 'added_tokens.json', sha256: '9715fd2243b6f06a5858b5e32950d2853f73dd5bc201aafcf76f5082a2d8acd1', bytes: 34604 },
|
|
19
|
+
{ name: 'generation_config.json', sha256: 'f5c67e5a4f7102f8cb4d058bc95da276bbc19eeec997267c3bb0f25ef68facd1', bytes: 3772 },
|
|
20
|
+
{ name: 'preprocessor_config.json', sha256: 'a6a76d28c93edb273669eb9e0b0636a2bddbb1272c3261e47b7ca6dfdbac1b8d', bytes: 339 },
|
|
21
|
+
{ name: 'config.json', sha256: '46aeea0a406afbeb563fc8e59ca10609203df4299af6a83f73752fef369efd2d', bytes: 2243 },
|
|
22
|
+
],
|
|
23
|
+
},
|
|
24
|
+
base: {
|
|
25
|
+
repo: 'onnx-community/whisper-base',
|
|
26
|
+
revision: '27a07b4b52b3a4c5886134bb4320e93e1a4bbc7c',
|
|
27
|
+
files: [
|
|
28
|
+
{ name: 'onnx/encoder_model_quantized.onnx', sha256: '5862993336bf33acd23736071aae2b32261d3b1b2f37780194460d4ef974dd46', bytes: 23201314 },
|
|
29
|
+
{ name: 'onnx/decoder_model_merged_q4.onnx', sha256: '09f83b71ceedc97dab1d90b914715dc532a646a147abda11d83c64867b7c319c', bytes: 123602419 },
|
|
30
|
+
{ name: 'vocab.json', sha256: '50d6a919f0a0601d56a04eb583c780d18553aa388254ba3158eb6a00f13e2c1a', bytes: 1036584 },
|
|
31
|
+
{ name: 'added_tokens.json', sha256: '9715fd2243b6f06a5858b5e32950d2853f73dd5bc201aafcf76f5082a2d8acd1', bytes: 34604 },
|
|
32
|
+
{ name: 'generation_config.json', sha256: '61070cf8de25b1e9256e8e102ded49d8d24a8369ed36ef84fdf21549e68125a0', bytes: 3832 },
|
|
33
|
+
{ name: 'preprocessor_config.json', sha256: 'a6a76d28c93edb273669eb9e0b0636a2bddbb1272c3261e47b7ca6dfdbac1b8d', bytes: 339 },
|
|
34
|
+
{ name: 'config.json', sha256: 'f4d0608f7d918166da7edb3e188de5ef1bfe70d9802e785d271fd88111e9cf4b', bytes: 2243 },
|
|
35
|
+
],
|
|
36
|
+
},
|
|
37
|
+
small: {
|
|
38
|
+
repo: 'onnx-community/whisper-small',
|
|
39
|
+
revision: '36050c46d777d46dc4b5f43f6d90574fc38f8732',
|
|
40
|
+
files: [
|
|
41
|
+
{ name: 'onnx/encoder_model_quantized.onnx', sha256: 'a43a83f3c5361cd591cfa7c36f14b43cf7cb22f47a415cc14a8d557be800fa92', bytes: 92326160 },
|
|
42
|
+
{ name: 'onnx/decoder_model_merged_q4.onnx', sha256: '795c61b344576719c2b249cc9911c78b4cc552c8c6a5407be21a3380a0791b13', bytes: 233149327 },
|
|
43
|
+
{ name: 'vocab.json', sha256: '50d6a919f0a0601d56a04eb583c780d18553aa388254ba3158eb6a00f13e2c1a', bytes: 1036584 },
|
|
44
|
+
{ name: 'added_tokens.json', sha256: '9715fd2243b6f06a5858b5e32950d2853f73dd5bc201aafcf76f5082a2d8acd1', bytes: 34604 },
|
|
45
|
+
{ name: 'generation_config.json', sha256: 'f538b28220c6a6d6f1af1458d4141cacb4ef4963df3de98a19490440c412ddf0', bytes: 3893 },
|
|
46
|
+
{ name: 'preprocessor_config.json', sha256: 'a6a76d28c93edb273669eb9e0b0636a2bddbb1272c3261e47b7ca6dfdbac1b8d', bytes: 339 },
|
|
47
|
+
{ name: 'config.json', sha256: '457854d452f17661e197d74aee12b8e74fb75ba30ebfaa7426d0d61ea1e08a18', bytes: 2227 },
|
|
48
|
+
],
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
export const DEFAULT_WHISPER_SIZE = 'base';
|
|
52
|
+
// Whisper's feature extractor and encoder are fixed at 16 kHz mono.
|
|
53
|
+
export const WHISPER_SAMPLE_RATE = 16000;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"decoder.d.ts","sourceRoot":"","sources":["../../../src/voice/whisper/decoder.ts"],"names":[],"mappings":"AAuBA,wBAAgB,UAAU,CACxB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC7B,OAAO,GAAE,QAAQ,CAAC,MAAM,CAAM,GAC7B,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAKrB;AAID,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,CAWpF"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Whisper's tokenizer is GPT-2's byte-level BPE: every vocabulary entry is a string of
|
|
2
|
+
// stand-in characters, one per byte. Decoding only needs the reverse map; encoding is
|
|
3
|
+
// never needed (the prompt is special tokens only).
|
|
4
|
+
// GPT-2 bytes_to_unicode, reversed: stand-in character -> byte.
|
|
5
|
+
const BYTE_OF = (() => {
|
|
6
|
+
const bytes = [];
|
|
7
|
+
for (let b = 33; b <= 126; b++)
|
|
8
|
+
bytes.push(b);
|
|
9
|
+
for (let b = 161; b <= 172; b++)
|
|
10
|
+
bytes.push(b);
|
|
11
|
+
for (let b = 174; b <= 255; b++)
|
|
12
|
+
bytes.push(b);
|
|
13
|
+
const chars = bytes.slice();
|
|
14
|
+
let n = 0;
|
|
15
|
+
for (let b = 0; b < 256; b++) {
|
|
16
|
+
if (!bytes.includes(b)) {
|
|
17
|
+
bytes.push(b);
|
|
18
|
+
chars.push(256 + n++);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return new Map(bytes.map((b, i) => [String.fromCharCode(chars[i]), b]));
|
|
22
|
+
})();
|
|
23
|
+
// vocab.json (token -> id) to id -> token, leaving out the special tokens: they carry no
|
|
24
|
+
// text, so decoding skips them.
|
|
25
|
+
export function parseVocab(vocab, special = []) {
|
|
26
|
+
const skip = new Set(special);
|
|
27
|
+
const out = new Map();
|
|
28
|
+
for (const [token, id] of Object.entries(vocab))
|
|
29
|
+
if (!skip.has(id))
|
|
30
|
+
out.set(id, token);
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
// Ids missing from the vocabulary (special tokens) are skipped. A multi-byte character
|
|
34
|
+
// split across tokens is reassembled because all bytes are joined before UTF-8 decoding.
|
|
35
|
+
export function byteDecode(ids, vocab) {
|
|
36
|
+
const bytes = [];
|
|
37
|
+
for (const id of ids) {
|
|
38
|
+
const token = vocab.get(id);
|
|
39
|
+
if (token === undefined)
|
|
40
|
+
continue;
|
|
41
|
+
for (const ch of token) {
|
|
42
|
+
const b = BYTE_OF.get(ch);
|
|
43
|
+
if (b !== undefined)
|
|
44
|
+
bytes.push(b);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return Buffer.from(bytes).toString('utf8');
|
|
48
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { BuiltinTranscriber } from '../../cli/web/voice_proxy.js';
|
|
2
|
+
import { type WhisperSize } from './catalog.js';
|
|
3
|
+
import { type WhisperModel } from './inference.js';
|
|
4
|
+
export type WhisperLoader = (size: WhisperSize) => Promise<WhisperModel>;
|
|
5
|
+
export declare function setWhisperLoaderForTest(l: WhisperLoader | null): void;
|
|
6
|
+
export declare function releaseWhisperModels(): Promise<void>;
|
|
7
|
+
export declare const transcribeBuiltin: BuiltinTranscriber;
|
|
8
|
+
//# sourceMappingURL=engine.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../../src/voice/whisper/engine.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAGvE,OAAO,EAA6D,KAAK,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3G,OAAO,EAAoC,KAAK,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAErF,MAAM,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,WAAW,KAAK,OAAO,CAAC,YAAY,CAAC,CAAC;AASzE,wBAAgB,uBAAuB,CAAC,CAAC,EAAE,aAAa,GAAG,IAAI,GAAG,IAAI,CAErE;AAqBD,wBAAsB,oBAAoB,IAAI,OAAO,CAAC,IAAI,CAAC,CAI1D;AAOD,eAAO,MAAM,iBAAiB,EAAE,kBA6B/B,CAAC"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// The built-in transcription engine: one warm Whisper model at a time, calls
|
|
2
|
+
// serialized, audio over 30 s split into windows and joined. Shares the ONNX runtime
|
|
3
|
+
// the built-in voice downloads (and loads) — see voice/pocket/engine.ts.
|
|
4
|
+
import { existsSync } from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import { loadOnnxRuntime } from '../pocket/engine.js';
|
|
7
|
+
import { runtimeEntry, whisperDir } from '../pocket/install.js';
|
|
8
|
+
import { DEFAULT_WHISPER_SIZE, WHISPER_MODELS, WHISPER_SAMPLE_RATE } from './catalog.js';
|
|
9
|
+
import { createWhisperModel, splitWindows } from './inference.js';
|
|
10
|
+
// Physical cores: the encoder scales with threads (6 beat 4 on a 6-core Zen 1),
|
|
11
|
+
// the decoder does not care.
|
|
12
|
+
const threads = () => Math.max(1, Math.floor(os.availableParallelism() / 2));
|
|
13
|
+
const defaultLoader = async (size) => createWhisperModel(loadOnnxRuntime(), whisperDir(size), { threads: threads() });
|
|
14
|
+
let loader = defaultLoader;
|
|
15
|
+
export function setWhisperLoaderForTest(l) {
|
|
16
|
+
loader = l ?? defaultLoader;
|
|
17
|
+
}
|
|
18
|
+
let slot = null;
|
|
19
|
+
function closeSlot(s) {
|
|
20
|
+
return s.tail
|
|
21
|
+
.then(() => s.model)
|
|
22
|
+
.then((m) => m.close())
|
|
23
|
+
.catch(() => { });
|
|
24
|
+
}
|
|
25
|
+
function slotFor(size) {
|
|
26
|
+
if (slot?.size === size)
|
|
27
|
+
return slot;
|
|
28
|
+
if (slot)
|
|
29
|
+
void closeSlot(slot);
|
|
30
|
+
const s = { size, model: loader(size), tail: Promise.resolve() };
|
|
31
|
+
s.model.catch(() => slot === s && (slot = null));
|
|
32
|
+
slot = s;
|
|
33
|
+
return s;
|
|
34
|
+
}
|
|
35
|
+
export async function releaseWhisperModels() {
|
|
36
|
+
const s = slot;
|
|
37
|
+
slot = null;
|
|
38
|
+
if (s)
|
|
39
|
+
await closeSlot(s);
|
|
40
|
+
}
|
|
41
|
+
const text = (status, body) => new Response(body, { status });
|
|
42
|
+
/** Primary subtag of the configured language, or null to let Whisper detect it. */
|
|
43
|
+
const languageOf = (voice) => voice.lang?.split(/[-_]/)[0]?.trim().toLowerCase() || null;
|
|
44
|
+
export const transcribeBuiltin = async (voice, audio, signal) => {
|
|
45
|
+
const size = voice.sttBuiltinModel ?? DEFAULT_WHISPER_SIZE;
|
|
46
|
+
if (!Object.hasOwn(WHISPER_MODELS, size))
|
|
47
|
+
return text(400, `Unknown built-in transcription model: ${size}.`);
|
|
48
|
+
if (!existsSync(runtimeEntry()))
|
|
49
|
+
return text(409, 'The built-in voice runtime is not installed. Install a transcription model in Settings → Voice.');
|
|
50
|
+
if (!existsSync(whisperDir(size)))
|
|
51
|
+
return text(409, `The ${size} transcription model is not installed. Install it in Settings → Voice.`);
|
|
52
|
+
// Take a turn on the model: one transcription at a time, in arrival order.
|
|
53
|
+
const s = slotFor(size);
|
|
54
|
+
let release;
|
|
55
|
+
const prev = s.tail;
|
|
56
|
+
s.tail = new Promise((r) => (release = r));
|
|
57
|
+
await prev;
|
|
58
|
+
try {
|
|
59
|
+
const model = await s.model;
|
|
60
|
+
const lang = languageOf(voice);
|
|
61
|
+
const parts = [];
|
|
62
|
+
for (const window of splitWindows(audio, WHISPER_SAMPLE_RATE)) {
|
|
63
|
+
if (signal.aborted)
|
|
64
|
+
return new Response(null, { status: 204 });
|
|
65
|
+
const t = (await model.transcribe(window, lang, signal)).trim();
|
|
66
|
+
if (t)
|
|
67
|
+
parts.push(t);
|
|
68
|
+
}
|
|
69
|
+
return Response.json({ text: parts.join(' ') });
|
|
70
|
+
}
|
|
71
|
+
catch (e) {
|
|
72
|
+
return text(500, e instanceof Error ? e.message : String(e));
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
release();
|
|
76
|
+
}
|
|
77
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare const SAMPLE_RATE = 16000;
|
|
2
|
+
export declare const N_FFT = 400;
|
|
3
|
+
export declare const HOP_LENGTH = 160;
|
|
4
|
+
export declare const N_MELS = 80;
|
|
5
|
+
export declare const N_SAMPLES: number;
|
|
6
|
+
export declare const N_FRAMES: number;
|
|
7
|
+
export declare function makeFFT(n: number): (inR: Float64Array, inI: Float64Array, outR: Float64Array, outI: Float64Array) => void;
|
|
8
|
+
export declare function melFilters(nMels?: number, nFft?: number, sampleRate?: number): Float64Array;
|
|
9
|
+
export declare function logMel(samples: Float32Array): Float32Array;
|
|
10
|
+
//# sourceMappingURL=features.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features.d.ts","sourceRoot":"","sources":["../../../src/voice/whisper/features.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,WAAW,QAAQ,CAAC;AACjC,eAAO,MAAM,KAAK,MAAM,CAAC;AACzB,eAAO,MAAM,UAAU,MAAM,CAAC;AAC9B,eAAO,MAAM,MAAM,KAAK,CAAC;AACzB,eAAO,MAAM,SAAS,QAAmB,CAAC;AAC1C,eAAO,MAAM,QAAQ,QAAyB,CAAC;AAO/C,wBAAgB,OAAO,CACrB,CAAC,EAAE,MAAM,GACR,CAAC,GAAG,EAAE,YAAY,EAAE,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,YAAY,KAAK,IAAI,CA+DxF;AASD,wBAAgB,UAAU,CAAC,KAAK,SAAS,EAAE,IAAI,SAAQ,EAAE,UAAU,SAAc,GAAG,YAAY,CAkB/F;AAiBD,wBAAgB,MAAM,CAAC,OAAO,EAAE,YAAY,GAAG,YAAY,CAyC1D"}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// Whisper log-mel features with the semantics of HF WhisperFeatureExtractor (measured to
|
|
2
|
+
// match faster-whisper's extractor to 3.8e-6): 16 kHz audio padded to 30 s, STFT with
|
|
3
|
+
// n_fft 400 / hop 160 / periodic Hann / reflect padding, power spectrum, 80 Slaney mel
|
|
4
|
+
// bins (the ONNX export ships no filterbank, so it is computed here), log10, clamp to
|
|
5
|
+
// max - 8, (x + 4) / 4.
|
|
6
|
+
export const SAMPLE_RATE = 16000;
|
|
7
|
+
export const N_FFT = 400;
|
|
8
|
+
export const HOP_LENGTH = 160;
|
|
9
|
+
export const N_MELS = 80;
|
|
10
|
+
export const N_SAMPLES = 30 * SAMPLE_RATE; // the encoder's fixed 30 s window
|
|
11
|
+
export const N_FRAMES = N_SAMPLES / HOP_LENGTH;
|
|
12
|
+
const N_BINS = N_FFT / 2 + 1;
|
|
13
|
+
const LOG_FLOOR = -10; // log10(1e-10), the value of an all-zero frame
|
|
14
|
+
// Mixed-radix FFT for any length with small factors (400 = 4 * 4 * 5 * 5). Writes the
|
|
15
|
+
// complex spectrum of (inR, inI) into (outR, outI).
|
|
16
|
+
export function makeFFT(n) {
|
|
17
|
+
const factors = [];
|
|
18
|
+
let m = n;
|
|
19
|
+
for (const p of [4, 2, 3, 5, 7]) {
|
|
20
|
+
while (m % p === 0) {
|
|
21
|
+
factors.push(p);
|
|
22
|
+
m /= p;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
if (m !== 1)
|
|
26
|
+
factors.push(m);
|
|
27
|
+
const cos = new Float64Array(n);
|
|
28
|
+
const sin = new Float64Array(n);
|
|
29
|
+
for (let i = 0; i < n; i++) {
|
|
30
|
+
cos[i] = Math.cos((-2 * Math.PI * i) / n);
|
|
31
|
+
sin[i] = Math.sin((-2 * Math.PI * i) / n);
|
|
32
|
+
}
|
|
33
|
+
const maxP = Math.max(1, ...factors);
|
|
34
|
+
const tr = new Float64Array(maxP);
|
|
35
|
+
const ti = new Float64Array(maxP);
|
|
36
|
+
const rec = (inR, inI, inOff, stride, len, oR, oI, oOff, fi) => {
|
|
37
|
+
if (len === 1) {
|
|
38
|
+
oR[oOff] = inR[inOff];
|
|
39
|
+
oI[oOff] = inI[inOff];
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
const p = factors[fi];
|
|
43
|
+
const sub = len / p;
|
|
44
|
+
const tw = n / len;
|
|
45
|
+
for (let q = 0; q < p; q++)
|
|
46
|
+
rec(inR, inI, inOff + q * stride, stride * p, sub, oR, oI, oOff + q * sub, fi + 1);
|
|
47
|
+
for (let k = 0; k < sub; k++) {
|
|
48
|
+
for (let q = 0; q < p; q++) {
|
|
49
|
+
tr[q] = oR[oOff + q * sub + k];
|
|
50
|
+
ti[q] = oI[oOff + q * sub + k];
|
|
51
|
+
}
|
|
52
|
+
for (let s = 0; s < p; s++) {
|
|
53
|
+
const kk = k + s * sub;
|
|
54
|
+
let ar = 0;
|
|
55
|
+
let ai = 0;
|
|
56
|
+
for (let q = 0; q < p; q++) {
|
|
57
|
+
const idx = ((q * kk) % len) * tw;
|
|
58
|
+
const c = cos[idx];
|
|
59
|
+
const d = sin[idx];
|
|
60
|
+
ar += tr[q] * c - ti[q] * d;
|
|
61
|
+
ai += tr[q] * d + ti[q] * c;
|
|
62
|
+
}
|
|
63
|
+
oR[oOff + kk] = ar;
|
|
64
|
+
oI[oOff + kk] = ai;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
return (inR, inI, outR, outI) => rec(inR, inI, 0, 1, n, outR, outI, 0, 0);
|
|
69
|
+
}
|
|
70
|
+
// Slaney mel scale and area-normalized triangles (librosa.filters.mel(htk=False,
|
|
71
|
+
// norm='slaney'), as HF WhisperFeatureExtractor). Row-major [nMels][nFft / 2 + 1].
|
|
72
|
+
const hzToMel = (f) => f < 1000 ? (3 * f) / 200 : 15 + (Math.log(f / 1000) * 27) / Math.log(6.4);
|
|
73
|
+
const melToHz = (m) => m < 15 ? (200 * m) / 3 : 1000 * Math.exp((Math.log(6.4) / 27) * (m - 15));
|
|
74
|
+
export function melFilters(nMels = N_MELS, nFft = N_FFT, sampleRate = SAMPLE_RATE) {
|
|
75
|
+
const nBins = nFft / 2 + 1;
|
|
76
|
+
const mMin = hzToMel(0);
|
|
77
|
+
const mMax = hzToMel(sampleRate / 2);
|
|
78
|
+
const pts = Array.from({ length: nMels + 2 }, (_, i) => melToHz(mMin + ((mMax - mMin) * i) / (nMels + 1)));
|
|
79
|
+
const fb = new Float64Array(nMels * nBins);
|
|
80
|
+
for (let m = 0; m < nMels; m++) {
|
|
81
|
+
const enorm = 2 / (pts[m + 2] - pts[m]);
|
|
82
|
+
for (let k = 0; k < nBins; k++) {
|
|
83
|
+
const f = (k * sampleRate) / nFft;
|
|
84
|
+
const down = (f - pts[m]) / (pts[m + 1] - pts[m]);
|
|
85
|
+
const up = (pts[m + 2] - f) / (pts[m + 2] - pts[m + 1]);
|
|
86
|
+
fb[m * nBins + k] = Math.max(0, Math.min(down, up)) * enorm;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return fb;
|
|
90
|
+
}
|
|
91
|
+
let tables = null;
|
|
92
|
+
function getTables() {
|
|
93
|
+
tables ??= {
|
|
94
|
+
fft: makeFFT(N_FFT),
|
|
95
|
+
fb: melFilters(),
|
|
96
|
+
hann: Float64Array.from({ length: N_FFT }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / N_FFT)),
|
|
97
|
+
};
|
|
98
|
+
return tables;
|
|
99
|
+
}
|
|
100
|
+
// [N_MELS * N_FRAMES], row-major by mel bin. Input is 16 kHz mono; anything past 30 s is
|
|
101
|
+
// ignored (callers split longer audio first).
|
|
102
|
+
export function logMel(samples) {
|
|
103
|
+
const { fft, fb, hann } = getTables();
|
|
104
|
+
const len = Math.min(samples.length, N_SAMPLES);
|
|
105
|
+
const x = new Float64Array(N_SAMPLES);
|
|
106
|
+
x.set(samples.subarray(0, len));
|
|
107
|
+
const pad = N_FFT / 2;
|
|
108
|
+
const mel = new Float32Array(N_MELS * N_FRAMES).fill(LOG_FLOOR);
|
|
109
|
+
const fr = new Float64Array(N_FFT);
|
|
110
|
+
const fi = new Float64Array(N_FFT);
|
|
111
|
+
const oR = new Float64Array(N_FFT);
|
|
112
|
+
const oI = new Float64Array(N_FFT);
|
|
113
|
+
const power = new Float64Array(N_BINS);
|
|
114
|
+
let max = -Infinity;
|
|
115
|
+
for (let t = 0; t < N_FRAMES; t++) {
|
|
116
|
+
const start = t * HOP_LENGTH - pad;
|
|
117
|
+
if (start >= len) {
|
|
118
|
+
// The frame lies entirely in the zero padding.
|
|
119
|
+
max = Math.max(max, LOG_FLOOR);
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
for (let i = 0; i < N_FFT; i++) {
|
|
123
|
+
let idx = start + i;
|
|
124
|
+
if (idx < 0)
|
|
125
|
+
idx = -idx;
|
|
126
|
+
else if (idx >= N_SAMPLES)
|
|
127
|
+
idx = 2 * (N_SAMPLES - 1) - idx; // reflect padding
|
|
128
|
+
fr[i] = x[idx] * hann[i];
|
|
129
|
+
fi[i] = 0;
|
|
130
|
+
}
|
|
131
|
+
fft(fr, fi, oR, oI);
|
|
132
|
+
for (let k = 0; k < N_BINS; k++)
|
|
133
|
+
power[k] = oR[k] * oR[k] + oI[k] * oI[k];
|
|
134
|
+
for (let m = 0; m < N_MELS; m++) {
|
|
135
|
+
let s = 0;
|
|
136
|
+
const row = m * N_BINS;
|
|
137
|
+
for (let k = 0; k < N_BINS; k++)
|
|
138
|
+
s += fb[row + k] * power[k];
|
|
139
|
+
const v = Math.log10(Math.max(s, 1e-10));
|
|
140
|
+
mel[m * N_FRAMES + t] = v;
|
|
141
|
+
if (v > max)
|
|
142
|
+
max = v;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const floor = max - 8;
|
|
146
|
+
for (let i = 0; i < mel.length; i++)
|
|
147
|
+
mel[i] = (Math.max(mel[i], floor) + 4) / 4;
|
|
148
|
+
return mel;
|
|
149
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { OrtModule } from '../pocket/inference.js';
|
|
2
|
+
export interface WhisperModel {
|
|
3
|
+
transcribe(audio: Float32Array, lang: string | null, signal: AbortSignal): Promise<string>;
|
|
4
|
+
close(): Promise<void>;
|
|
5
|
+
}
|
|
6
|
+
export declare const WHISPER_GRAPHS: {
|
|
7
|
+
readonly encoder: "encoder_model_quantized.onnx";
|
|
8
|
+
readonly decoder: "decoder_model_merged_q4.onnx";
|
|
9
|
+
};
|
|
10
|
+
export declare const WHISPER_FILES: readonly ["config.json", "generation_config.json", "added_tokens.json", "vocab.json"];
|
|
11
|
+
export declare const MAX_NEW_TOKENS = 224;
|
|
12
|
+
export declare function modelFile(dir: string, name: string): string;
|
|
13
|
+
export declare function createWhisperModel(ort: OrtModule, dir: string, opts: {
|
|
14
|
+
threads: number;
|
|
15
|
+
}): Promise<WhisperModel>;
|
|
16
|
+
export declare function splitWindows(audio: Float32Array, rate?: number): Float32Array[];
|
|
17
|
+
//# sourceMappingURL=inference.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inference.d.ts","sourceRoot":"","sources":["../../../src/voice/whisper/inference.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,SAAS,EAAyB,MAAM,wBAAwB,CAAC;AAI/E,MAAM,WAAW,YAAY;IAG3B,UAAU,CAAC,KAAK,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC3F,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAID,eAAO,MAAM,cAAc;;;CAGjB,CAAC;AACX,eAAO,MAAM,aAAa,uFAKhB,CAAC;AAGX,eAAO,MAAM,cAAc,MAAM,CAAC;AAWlC,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAG3D;AAkBD,wBAAsB,kBAAkB,CACtC,GAAG,EAAE,SAAS,EACd,GAAG,EAAE,MAAM,EACX,IAAI,EAAE;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,GACxB,OAAO,CAAC,YAAY,CAAC,CA6BvB;AAuKD,wBAAgB,YAAY,CAAC,KAAK,EAAE,YAAY,EAAE,IAAI,GAAE,MAAoB,GAAG,YAAY,EAAE,CA2B5F"}
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
// Own inference loop over a Whisper ONNX export (HF/optimum layout): 16 kHz audio ->
|
|
2
|
+
// log-mel (features.ts) -> encoder over the fixed 30 s window -> greedy decoding on the
|
|
3
|
+
// merged decoder with KV cache (`use_cache_branch`) -> GPT-2 byte decoding (decoder.ts).
|
|
4
|
+
// The ONNX runtime is passed in (downloaded at runtime, never a package dependency).
|
|
5
|
+
import { existsSync } from 'node:fs';
|
|
6
|
+
import { readFile } from 'node:fs/promises';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { byteDecode, parseVocab } from './decoder.js';
|
|
9
|
+
import { logMel, N_FRAMES, N_MELS, N_SAMPLES, SAMPLE_RATE } from './features.js';
|
|
10
|
+
// int8 encoder + q4 decoder: the int8 decoder is ~2.5x slower per token on CPUs without
|
|
11
|
+
// VNNI, encoder speed is the same across variants (spike measurements).
|
|
12
|
+
export const WHISPER_GRAPHS = {
|
|
13
|
+
encoder: 'encoder_model_quantized.onnx',
|
|
14
|
+
decoder: 'decoder_model_merged_q4.onnx',
|
|
15
|
+
};
|
|
16
|
+
export const WHISPER_FILES = [
|
|
17
|
+
'config.json',
|
|
18
|
+
'generation_config.json',
|
|
19
|
+
'added_tokens.json',
|
|
20
|
+
'vocab.json',
|
|
21
|
+
];
|
|
22
|
+
// Half the decoder's 448 positions, as openai-whisper / HF generate.
|
|
23
|
+
export const MAX_NEW_TOKENS = 224;
|
|
24
|
+
// Peak amplitude below which a window is silence (-60 dBFS): Whisper hallucinates on
|
|
25
|
+
// silence ("Thanks for watching"), so it is never fed to the model.
|
|
26
|
+
const SILENCE_PEAK = 1e-3;
|
|
27
|
+
const WINDOW_SECONDS = 30;
|
|
28
|
+
const CUT_SEARCH_SECONDS = 5;
|
|
29
|
+
const CUT_SPAN_SECONDS = 0.5;
|
|
30
|
+
// A model directory holds the HF layout (graphs under onnx/) or everything flat.
|
|
31
|
+
export function modelFile(dir, name) {
|
|
32
|
+
for (const path of [join(dir, 'onnx', name), join(dir, name)])
|
|
33
|
+
if (existsSync(path))
|
|
34
|
+
return path;
|
|
35
|
+
throw new Error(`Whisper model file ${name} is missing in ${dir}`);
|
|
36
|
+
}
|
|
37
|
+
const readJson = async (dir, name) => JSON.parse(await readFile(modelFile(dir, name), 'utf8'));
|
|
38
|
+
export async function createWhisperModel(ort, dir, opts) {
|
|
39
|
+
const config = await readJson(dir, 'config.json');
|
|
40
|
+
const gen = await readJson(dir, 'generation_config.json');
|
|
41
|
+
const added = await readJson(dir, 'added_tokens.json');
|
|
42
|
+
const vocab = parseVocab(await readJson(dir, 'vocab.json'), Object.values(added));
|
|
43
|
+
const sessionOptions = {
|
|
44
|
+
intraOpNumThreads: Math.max(1, opts.threads),
|
|
45
|
+
interOpNumThreads: 1,
|
|
46
|
+
executionMode: 'sequential',
|
|
47
|
+
};
|
|
48
|
+
const encoder = await ort.InferenceSession.create(modelFile(dir, WHISPER_GRAPHS.encoder), sessionOptions);
|
|
49
|
+
let decoder;
|
|
50
|
+
try {
|
|
51
|
+
decoder = await ort.InferenceSession.create(modelFile(dir, WHISPER_GRAPHS.decoder), sessionOptions);
|
|
52
|
+
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
await encoder.release().catch(() => { });
|
|
55
|
+
throw err;
|
|
56
|
+
}
|
|
57
|
+
return new Model(ort, config, gen, Object.values(added), vocab, encoder, decoder);
|
|
58
|
+
}
|
|
59
|
+
class Model {
|
|
60
|
+
ort;
|
|
61
|
+
config;
|
|
62
|
+
gen;
|
|
63
|
+
specialIds;
|
|
64
|
+
vocab;
|
|
65
|
+
encoder;
|
|
66
|
+
decoder;
|
|
67
|
+
closed = false;
|
|
68
|
+
// Suppression masks (1 = never emitted), sized from the first logits seen.
|
|
69
|
+
masks = null;
|
|
70
|
+
constructor(ort, config, gen, specialIds, vocab, encoder, decoder) {
|
|
71
|
+
this.ort = ort;
|
|
72
|
+
this.config = config;
|
|
73
|
+
this.gen = gen;
|
|
74
|
+
this.specialIds = specialIds;
|
|
75
|
+
this.vocab = vocab;
|
|
76
|
+
this.encoder = encoder;
|
|
77
|
+
this.decoder = decoder;
|
|
78
|
+
}
|
|
79
|
+
async transcribe(audio, lang, signal) {
|
|
80
|
+
if (this.closed)
|
|
81
|
+
throw new Error('Whisper model is closed');
|
|
82
|
+
if (audio.length > N_SAMPLES)
|
|
83
|
+
throw new Error('Whisper window longer than 30 s; split it with splitWindows');
|
|
84
|
+
signal.throwIfAborted();
|
|
85
|
+
if (peak(audio) < SILENCE_PEAK)
|
|
86
|
+
return '';
|
|
87
|
+
const { ort, gen } = this;
|
|
88
|
+
const features = new ort.Tensor('float32', logMel(audio), [1, N_MELS, N_FRAMES]);
|
|
89
|
+
const { last_hidden_state: hidden } = await this.encoder.run({ input_features: features });
|
|
90
|
+
signal.throwIfAborted();
|
|
91
|
+
const tail = [gen.task_to_id.transcribe, gen.no_timestamps_token_id];
|
|
92
|
+
let langId = lang ? gen.lang_to_id[`<|${lang.toLowerCase().split(/[-_]/)[0]}|>`] : undefined;
|
|
93
|
+
if (langId === undefined) {
|
|
94
|
+
// Auto-detect: the language token Whisper itself would emit after SOT, in a pass of
|
|
95
|
+
// its own like faster-whisper. Continuing that pass with the rest of the prompt on
|
|
96
|
+
// the cache branch was measured to change the transcript.
|
|
97
|
+
const logits = await this.pass(hidden)([gen.decoder_start_token_id]);
|
|
98
|
+
langId = argmaxOf(logits, Object.values(gen.lang_to_id));
|
|
99
|
+
signal.throwIfAborted();
|
|
100
|
+
}
|
|
101
|
+
const step = this.pass(hidden);
|
|
102
|
+
let feed = [gen.decoder_start_token_id, langId, ...tail];
|
|
103
|
+
const tokens = [];
|
|
104
|
+
for (let n = 0; n < MAX_NEW_TOKENS; n++) {
|
|
105
|
+
signal.throwIfAborted();
|
|
106
|
+
const logits = await step(feed);
|
|
107
|
+
const masks = this.suppression(logits.length);
|
|
108
|
+
const token = argmaxUnmasked(logits, n === 0 ? masks.first : masks.any);
|
|
109
|
+
if (token === gen.eos_token_id || token < 0)
|
|
110
|
+
break;
|
|
111
|
+
tokens.push(token);
|
|
112
|
+
feed = [token];
|
|
113
|
+
}
|
|
114
|
+
return byteDecode(tokens, this.vocab).trim();
|
|
115
|
+
}
|
|
116
|
+
async close() {
|
|
117
|
+
if (this.closed)
|
|
118
|
+
return;
|
|
119
|
+
this.closed = true;
|
|
120
|
+
await Promise.allSettled([this.encoder.release(), this.decoder.release()]);
|
|
121
|
+
}
|
|
122
|
+
// A decoding pass: each call returns the logits of the last position for `ids` and
|
|
123
|
+
// advances the pass's own KV cache.
|
|
124
|
+
pass(hidden) {
|
|
125
|
+
const { ort } = this;
|
|
126
|
+
const past = this.emptyPast();
|
|
127
|
+
let cached = false;
|
|
128
|
+
return async (ids) => {
|
|
129
|
+
const out = await this.decoder.run({
|
|
130
|
+
input_ids: new ort.Tensor('int64', BigInt64Array.from(ids, BigInt), [1, ids.length]),
|
|
131
|
+
encoder_hidden_states: hidden,
|
|
132
|
+
use_cache_branch: new ort.Tensor('bool', Uint8Array.of(cached ? 1 : 0), [1]),
|
|
133
|
+
...past,
|
|
134
|
+
});
|
|
135
|
+
for (let l = 0; l < this.config.decoder_layers; l++) {
|
|
136
|
+
for (const kind of ['decoder.key', 'decoder.value']) {
|
|
137
|
+
past[`past_key_values.${l}.${kind}`] = output(out, `present.${l}.${kind}`);
|
|
138
|
+
}
|
|
139
|
+
// The cross-attention cache is computed by the no-cache branch only; the cache
|
|
140
|
+
// branch passes it through.
|
|
141
|
+
if (!cached) {
|
|
142
|
+
for (const kind of ['encoder.key', 'encoder.value']) {
|
|
143
|
+
past[`past_key_values.${l}.${kind}`] = output(out, `present.${l}.${kind}`);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
cached = true;
|
|
148
|
+
const logits = output(out, 'logits');
|
|
149
|
+
const size = logits.dims[2];
|
|
150
|
+
const data = logits.data;
|
|
151
|
+
return data.subarray(data.length - size);
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
// Step 0 runs the no-cache branch, which still requires the past inputs: empty
|
|
155
|
+
// [1, heads, 0, headDim] tensors.
|
|
156
|
+
emptyPast() {
|
|
157
|
+
const { decoder_attention_heads: heads, d_model, decoder_layers } = this.config;
|
|
158
|
+
const empty = new this.ort.Tensor('float32', new Float32Array(0), [
|
|
159
|
+
1,
|
|
160
|
+
heads,
|
|
161
|
+
0,
|
|
162
|
+
d_model / heads,
|
|
163
|
+
]);
|
|
164
|
+
const past = {};
|
|
165
|
+
for (let l = 0; l < decoder_layers; l++) {
|
|
166
|
+
for (const kind of ['decoder.key', 'decoder.value', 'encoder.key', 'encoder.value']) {
|
|
167
|
+
past[`past_key_values.${l}.${kind}`] = empty;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return past;
|
|
171
|
+
}
|
|
172
|
+
// Special tokens (timestamps, languages, tasks: everything in added_tokens.json but
|
|
173
|
+
// EOT) and generation_config's suppress_tokens; the first sampled token also excludes
|
|
174
|
+
// begin_suppress_tokens (a leading space, EOT).
|
|
175
|
+
suppression(size) {
|
|
176
|
+
if (this.masks?.any.length === size)
|
|
177
|
+
return this.masks;
|
|
178
|
+
const any = new Uint8Array(size);
|
|
179
|
+
const set = (mask, ids) => {
|
|
180
|
+
for (const id of ids)
|
|
181
|
+
if (id >= 0 && id < size)
|
|
182
|
+
mask[id] = 1;
|
|
183
|
+
};
|
|
184
|
+
set(any, this.specialIds);
|
|
185
|
+
set(any, this.gen.suppress_tokens ?? []);
|
|
186
|
+
any[this.gen.eos_token_id] = 0;
|
|
187
|
+
const first = any.slice();
|
|
188
|
+
set(first, this.gen.begin_suppress_tokens ?? []);
|
|
189
|
+
this.masks = { any, first };
|
|
190
|
+
return this.masks;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
function output(out, name) {
|
|
194
|
+
const t = out[name];
|
|
195
|
+
if (!t)
|
|
196
|
+
throw new Error(`Whisper decoder output ${name} is missing`);
|
|
197
|
+
return t;
|
|
198
|
+
}
|
|
199
|
+
function peak(audio) {
|
|
200
|
+
let max = 0;
|
|
201
|
+
for (const v of audio) {
|
|
202
|
+
const a = Math.abs(v);
|
|
203
|
+
if (a > max)
|
|
204
|
+
max = a;
|
|
205
|
+
}
|
|
206
|
+
return max;
|
|
207
|
+
}
|
|
208
|
+
function argmaxUnmasked(logits, mask) {
|
|
209
|
+
let best = -1;
|
|
210
|
+
let bestValue = -Infinity;
|
|
211
|
+
for (let i = 0; i < logits.length; i++) {
|
|
212
|
+
if (mask[i] || !(logits[i] > bestValue))
|
|
213
|
+
continue;
|
|
214
|
+
bestValue = logits[i];
|
|
215
|
+
best = i;
|
|
216
|
+
}
|
|
217
|
+
return best;
|
|
218
|
+
}
|
|
219
|
+
function argmaxOf(logits, ids) {
|
|
220
|
+
let best = ids[0];
|
|
221
|
+
for (const id of ids)
|
|
222
|
+
if (logits[id] > logits[best])
|
|
223
|
+
best = id;
|
|
224
|
+
return best;
|
|
225
|
+
}
|
|
226
|
+
// Splits audio longer than 30 s into consecutive windows of at most 30 s, each cut in
|
|
227
|
+
// the middle of the quietest 0.5 s within its last 5 s, so a cut rarely lands mid-word.
|
|
228
|
+
// The windows are views on `audio` and cover every sample, in order.
|
|
229
|
+
export function splitWindows(audio, rate = SAMPLE_RATE) {
|
|
230
|
+
const max = Math.floor(WINDOW_SECONDS * rate);
|
|
231
|
+
const span = Math.max(1, Math.round(CUT_SPAN_SECONDS * rate));
|
|
232
|
+
const search = Math.round(CUT_SEARCH_SECONDS * rate);
|
|
233
|
+
const windows = [];
|
|
234
|
+
let start = 0;
|
|
235
|
+
while (audio.length - start > max) {
|
|
236
|
+
// Candidate spans [s, s + span) with s + span <= start + max.
|
|
237
|
+
const from = start + max - search;
|
|
238
|
+
const to = start + max - span;
|
|
239
|
+
let energy = 0;
|
|
240
|
+
for (let i = from; i < from + span; i++)
|
|
241
|
+
energy += audio[i] * audio[i];
|
|
242
|
+
let best = from;
|
|
243
|
+
let bestEnergy = energy;
|
|
244
|
+
for (let s = from + 1; s <= to; s++) {
|
|
245
|
+
energy += audio[s + span - 1] * audio[s + span - 1] - audio[s - 1] * audio[s - 1];
|
|
246
|
+
if (energy < bestEnergy - 1e-9) {
|
|
247
|
+
bestEnergy = energy;
|
|
248
|
+
best = s;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
const cut = best + Math.floor(span / 2);
|
|
252
|
+
windows.push(audio.subarray(start, cut));
|
|
253
|
+
start = cut;
|
|
254
|
+
}
|
|
255
|
+
windows.push(audio.subarray(start));
|
|
256
|
+
return windows;
|
|
257
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Parse a RIFF/WAVE file that is exactly what the Whisper engine consumes:
|
|
2
|
+
* 16 kHz, mono, 16-bit integer PCM. Anything else throws a readable Error —
|
|
3
|
+
* the server has no resampler and must never feed garbage to the model. */
|
|
4
|
+
export declare function parseWav16kMono(buf: Uint8Array): Float32Array;
|
|
5
|
+
//# sourceMappingURL=wav.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wav.d.ts","sourceRoot":"","sources":["../../../src/voice/whisper/wav.ts"],"names":[],"mappings":"AAAA;;4EAE4E;AAC5E,wBAAgB,eAAe,CAAC,GAAG,EAAE,UAAU,GAAG,YAAY,CAmC7D"}
|