openwakeword-js 0.1.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,62 @@
1
+ # openWakeWord-JS
2
+
3
+ A high-accuracy, 100% logic-aligned JavaScript/TypeScript port of [openWakeWord](https://github.com/dscripka/openWakeWord). Designed for browser-first execution using ONNX Runtime Web, with Node.js support.
4
+
5
+ ## Credits & Acknowledgments
6
+ This package is a JavaScript port of the excellent work by **David Scripka**. For the full Python implementation, training scripts, and model details, please visit the original repository:
7
+ 👉 **[Original openWakeWord Repository](https://github.com/dscripka/openWakeWord)**
8
+
9
+ ## Key Features
10
+ - **Bit-Perfect Parity**: Matches the original Python implementation's Mel spectrogram transforms, sliding windows, and VAD gating logic.
11
+ - **Privacy First**: Voice processing runs **entirely on the user's local machine** (browser/Node.js). No audio data is ever sent to a server.
12
+ - **High Performance**: Leverages WebAssembly (WASM) with SIMD for hardware-accelerated inference.
13
+ - **Customizable**: Load any openWakeWord ONNX models directly.
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @openwakeword/js onnxruntime-web
19
+ ```
20
+
21
+ ## Required Assets
22
+ To run wake word detection, you need the following ONNX models (available in the original repo):
23
+ 1. `melspectrogram.onnx`: Audio feature extractor.
24
+ 2. `embedding_model.onnx`: Feature embedding generator.
25
+ 3. **Your Wake Word Model**: (e.g., `alexa.onnx`, `hey_deepa.onnx`).
26
+
27
+ ### Browser Requirements
28
+ When running in a browser, ensure you serve the ONNX Runtime WASM files or point to a CDN:
29
+ ```typescript
30
+ const model = new Model({
31
+ // ...
32
+ wasmPaths: 'https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/'
33
+ });
34
+ ```
35
+
36
+ ## Quick Start
37
+
38
+ ```typescript
39
+ import { Model } from '@openwakeword/js';
40
+
41
+ // 1. Initialize the model
42
+ const model = new Model({
43
+ wakewordModels: ['./models/my_wakeword.onnx'],
44
+ melspectrogramModelPath: './models/melspectrogram.onnx',
45
+ embeddingModelPath: './models/embedding_model.onnx',
46
+ vadModelPath: './models/silero_vad.onnx', // Optional
47
+ vadThreshold: 0.5, // Optional
48
+ inferenceFramework: 'onnx'
49
+ });
50
+
51
+ await model.init();
52
+
53
+ // 2. Feed audio chunks (16kHz, mono, Float32Array or Int16Array)
54
+ // Recommended chunk size: 1280 samples (80ms)
55
+ const audioChunk = ...;
56
+ const scores = await model.predict(audioChunk);
57
+
58
+ console.log(scores); // { "my_wakeword": 0.82 }
59
+ ```
60
+
61
+ ## License
62
+ Apache-2.0 (Matched with the original openWakeWord license)
package/dist/index.cjs ADDED
@@ -0,0 +1,277 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ Model: () => Model
34
+ });
35
+ module.exports = __toCommonJS(index_exports);
36
+ var ort = __toESM(require("onnxruntime-web"), 1);
37
+ var Model = class {
38
+ constructor(options) {
39
+ this.options = options;
40
+ const runtime = ort.env ? ort : globalThis.ort;
41
+ if (runtime && options.wasmPaths) {
42
+ runtime.env.wasm.wasmPaths = options.wasmPaths;
43
+ }
44
+ this.melContextBuffer = new Float32Array(this.MEL_CONTEXT).fill(0);
45
+ }
46
+ melSession = null;
47
+ embeddingSession = null;
48
+ vadSession = null;
49
+ customSessions = /* @__PURE__ */ new Map();
50
+ // Buffers
51
+ melBuffer = [];
52
+ embeddingBuffers = /* @__PURE__ */ new Map();
53
+ predictionBuffers = /* @__PURE__ */ new Map();
54
+ vadBuffer = [];
55
+ rawAudioRemainder = new Float32Array(0);
56
+ melContextBuffer;
57
+ // Seeding history
58
+ noiseSeededEmbeddings = /* @__PURE__ */ new Map();
59
+ // Constants
60
+ CHUNK_SIZE = 1280;
61
+ MEL_CONTEXT = 480;
62
+ SAMPLE_RATE = 16e3;
63
+ MEL_BINS = 32;
64
+ FRAMES_PER_CHUNK = 8;
65
+ MEL_WINDOW_SIZE = 76;
66
+ EMBEDDING_WINDOW_SIZE = 24;
67
+ MAX_MEL_FRAMES = 970;
68
+ INITIAL_FRAMES_SUPPRESS = 5;
69
+ PREDICTION_BUFFER_MAX = 30;
70
+ // VAD State (Silero VAD)
71
+ vadStateH = new Float32Array(2 * 1 * 64).fill(0);
72
+ vadStateC = new Float32Array(2 * 1 * 64).fill(0);
73
+ isLoaded = false;
74
+ async init() {
75
+ try {
76
+ this.melSession = await ort.InferenceSession.create(this.options.melspectrogramModelPath);
77
+ this.embeddingSession = await ort.InferenceSession.create(this.options.embeddingModelPath);
78
+ if (this.options.vadModelPath && this.options.vadThreshold && this.options.vadThreshold > 0) {
79
+ this.vadSession = await ort.InferenceSession.create(this.options.vadModelPath);
80
+ }
81
+ this.melBuffer = Array(this.MEL_WINDOW_SIZE).fill(0).map(() => new Float32Array(this.MEL_BINS).fill(1));
82
+ const warmNoise = new Float32Array(this.SAMPLE_RATE * 4);
83
+ for (let i = 0; i < warmNoise.length; i++) warmNoise[i] = Math.random() * 2e3 - 1e3;
84
+ const tempMelContext = new Float32Array(this.MEL_CONTEXT).fill(0);
85
+ const generatedEmbeddings = [];
86
+ for (let i = 0; i <= warmNoise.length - this.CHUNK_SIZE; i += this.CHUNK_SIZE) {
87
+ const chunk = warmNoise.subarray(i, i + this.CHUNK_SIZE);
88
+ const melInput = new Float32Array(this.CHUNK_SIZE + this.MEL_CONTEXT);
89
+ melInput.set(tempMelContext);
90
+ melInput.set(chunk, this.MEL_CONTEXT);
91
+ tempMelContext.set(chunk.subarray(this.CHUNK_SIZE - this.MEL_CONTEXT));
92
+ const melOutput = await this.runMelSpectrogram(melInput);
93
+ for (let f = 0; f < this.FRAMES_PER_CHUNK; f++) {
94
+ const frame = new Float32Array(this.MEL_BINS);
95
+ for (let b = 0; b < this.MEL_BINS; b++) {
96
+ const idx = f * this.MEL_BINS + b;
97
+ frame[b] = melOutput[idx] / 10 + 2;
98
+ }
99
+ this.melBuffer.push(frame);
100
+ }
101
+ while (this.melBuffer.length > this.MAX_MEL_FRAMES) this.melBuffer.shift();
102
+ const emb = await this.runEmbeddingModel();
103
+ generatedEmbeddings.push(emb);
104
+ }
105
+ for (const modelPath of this.options.wakewordModels) {
106
+ const session = await ort.InferenceSession.create(modelPath);
107
+ const name = this.extractModelName(modelPath);
108
+ this.customSessions.set(name, session);
109
+ const history = generatedEmbeddings.slice(-this.EMBEDDING_WINDOW_SIZE).map((e) => new Float32Array(e));
110
+ this.noiseSeededEmbeddings.set(name, history);
111
+ this.embeddingBuffers.set(name, history.map((e) => new Float32Array(e)));
112
+ this.predictionBuffers.set(name, []);
113
+ }
114
+ this.isLoaded = true;
115
+ console.log("OpenWakeWord models loaded and bit-perfectly aligned");
116
+ } catch (error) {
117
+ console.error("Failed to initialize OpenWakeWord models:", error);
118
+ throw error;
119
+ }
120
+ }
121
+ async predict(audio) {
122
+ if (!this.isLoaded) throw new Error("Model not initialized");
123
+ let pcmAudio;
124
+ if (audio instanceof Int16Array) {
125
+ pcmAudio = new Float32Array(audio.length);
126
+ for (let i = 0; i < audio.length; i++) pcmAudio[i] = audio[i];
127
+ } else {
128
+ let max = 0;
129
+ for (let i = 0; i < Math.min(audio.length, 1e3); i++) {
130
+ const abs = Math.abs(audio[i]);
131
+ if (abs > max) max = abs;
132
+ }
133
+ if (max <= 1) {
134
+ pcmAudio = new Float32Array(audio.length);
135
+ for (let i = 0; i < audio.length; i++) pcmAudio[i] = audio[i] * 32768;
136
+ } else {
137
+ pcmAudio = audio;
138
+ }
139
+ }
140
+ let combinedAudio = new Float32Array(this.rawAudioRemainder.length + pcmAudio.length);
141
+ combinedAudio.set(this.rawAudioRemainder);
142
+ combinedAudio.set(pcmAudio, this.rawAudioRemainder.length);
143
+ const scores = {};
144
+ for (const name of this.customSessions.keys()) scores[name] = 0;
145
+ let offset = 0;
146
+ while (offset + this.CHUNK_SIZE <= combinedAudio.length) {
147
+ const chunk = combinedAudio.subarray(offset, offset + this.CHUNK_SIZE);
148
+ offset += this.CHUNK_SIZE;
149
+ const melInput = new Float32Array(this.CHUNK_SIZE + this.MEL_CONTEXT);
150
+ melInput.set(this.melContextBuffer);
151
+ melInput.set(chunk, this.MEL_CONTEXT);
152
+ this.melContextBuffer.set(chunk.subarray(this.CHUNK_SIZE - this.MEL_CONTEXT));
153
+ if (this.vadSession && this.options.vadThreshold) {
154
+ const vadScore = await this.runVAD(chunk);
155
+ this.vadBuffer.push(vadScore);
156
+ while (this.vadBuffer.length > 30) this.vadBuffer.shift();
157
+ }
158
+ const melOutput = await this.runMelSpectrogram(melInput);
159
+ for (let f = 0; f < this.FRAMES_PER_CHUNK; f++) {
160
+ const frame = new Float32Array(this.MEL_BINS);
161
+ for (let b = 0; b < this.MEL_BINS; b++) {
162
+ const idx = f * this.MEL_BINS + b;
163
+ frame[b] = melOutput[idx] / 10 + 2;
164
+ }
165
+ this.melBuffer.push(frame);
166
+ }
167
+ while (this.melBuffer.length > this.MAX_MEL_FRAMES) this.melBuffer.shift();
168
+ const embedding = await this.runEmbeddingModel();
169
+ for (const [name, session] of this.customSessions.entries()) {
170
+ const embBuf = this.embeddingBuffers.get(name);
171
+ embBuf.shift();
172
+ embBuf.push(embedding);
173
+ let score = await this.runClassifier(name, session);
174
+ if (this.vadSession && this.options.vadThreshold) {
175
+ const window = this.vadBuffer.slice(-7, -4);
176
+ const maxVAD = window.length > 0 ? Math.max(...window) : 0;
177
+ if (maxVAD < this.options.vadThreshold) score = 0;
178
+ }
179
+ const predBuf = this.predictionBuffers.get(name);
180
+ predBuf.push(score);
181
+ while (predBuf.length > this.PREDICTION_BUFFER_MAX) predBuf.shift();
182
+ if (predBuf.length < this.INITIAL_FRAMES_SUPPRESS) {
183
+ score = 0;
184
+ } else if (this.options.patience?.[name] || this.options.debounceTime && this.options.debounceTime > 0) {
185
+ const threshold = this.options.thresholds?.[name] ?? 0.5;
186
+ if (this.options.patience?.[name]) {
187
+ const p = this.options.patience[name];
188
+ const recentScores = predBuf.slice(-p);
189
+ const countAbove = recentScores.filter((s) => s >= threshold).length;
190
+ if (countAbove < p) score = 0;
191
+ } else if (this.options.debounceTime) {
192
+ const framesToWait = Math.ceil(this.options.debounceTime / 0.08);
193
+ const recentScores = predBuf.slice(-framesToWait - 1, -1);
194
+ const alreadyTriggered = recentScores.some((s) => s >= threshold);
195
+ if (score >= threshold && alreadyTriggered) score = 0;
196
+ }
197
+ }
198
+ scores[name] = Math.max(scores[name], score);
199
+ }
200
+ }
201
+ this.rawAudioRemainder = combinedAudio.slice(offset);
202
+ return scores;
203
+ }
204
+ async runMelSpectrogram(input) {
205
+ const inputTensor = new ort.Tensor("float32", input, [1, input.length]);
206
+ const results = await this.melSession.run({ [this.melSession.inputNames[0]]: inputTensor });
207
+ return results[this.melSession.outputNames[0]].data;
208
+ }
209
+ async runEmbeddingModel() {
210
+ const windowData = new Float32Array(this.MEL_WINDOW_SIZE * this.MEL_BINS);
211
+ const startIdx = this.melBuffer.length - this.MEL_WINDOW_SIZE;
212
+ for (let t = 0; t < this.MEL_WINDOW_SIZE; t++) {
213
+ windowData.set(this.melBuffer[startIdx + t], t * this.MEL_BINS);
214
+ }
215
+ const windowTensor = new ort.Tensor("float32", windowData, [1, this.MEL_WINDOW_SIZE, this.MEL_BINS, 1]);
216
+ const results = await this.embeddingSession.run({ [this.embeddingSession.inputNames[0]]: windowTensor });
217
+ const output = results[this.embeddingSession.outputNames[0]].data;
218
+ const embedding = new Float32Array(96);
219
+ for (let i = 0; i < 96; i++) {
220
+ let v = output[i] ?? 0;
221
+ if (isNaN(v) || !isFinite(v)) v = 0;
222
+ embedding[i] = v;
223
+ }
224
+ return embedding;
225
+ }
226
+ async runClassifier(name, session) {
227
+ const embBuf = this.embeddingBuffers.get(name);
228
+ const predData = new Float32Array(this.EMBEDDING_WINDOW_SIZE * 96);
229
+ for (let t = 0; t < this.EMBEDDING_WINDOW_SIZE; t++) predData.set(embBuf[t], t * 96);
230
+ const predTensor = new ort.Tensor("float32", predData, [1, this.EMBEDDING_WINDOW_SIZE, 96]);
231
+ const results = await session.run({ [session.inputNames[0]]: predTensor });
232
+ return results[session.outputNames[0]].data[0];
233
+ }
234
+ async runVAD(chunk) {
235
+ const normalized = new Float32Array(chunk.length);
236
+ for (let i = 0; i < chunk.length; i++) normalized[i] = chunk[i] / 32768;
237
+ const srTensor = new ort.Tensor("int64", BigInt64Array.from([BigInt(this.SAMPLE_RATE)]), [1]);
238
+ const hTensor = new ort.Tensor("float32", this.vadStateH, [2, 1, 64]);
239
+ const cTensor = new ort.Tensor("float32", this.vadStateC, [2, 1, 64]);
240
+ const inputTensor = new ort.Tensor("float32", normalized, [1, chunk.length]);
241
+ const feeds = {
242
+ [this.vadSession.inputNames[0]]: inputTensor,
243
+ [this.vadSession.inputNames[1]]: srTensor,
244
+ [this.vadSession.inputNames[2]]: hTensor,
245
+ [this.vadSession.inputNames[3]]: cTensor
246
+ };
247
+ const results = await this.vadSession.run(feeds);
248
+ this.vadStateH = results[this.vadSession.outputNames[1]].data;
249
+ this.vadStateC = results[this.vadSession.outputNames[2]].data;
250
+ return results[this.vadSession.outputNames[0]].data[0];
251
+ }
252
+ extractModelName(path) {
253
+ const base = path.split("/").pop() || path;
254
+ return base.replace(".onnx", "").replace(".tflite", "");
255
+ }
256
+ reset() {
257
+ this.melBuffer = Array(this.MEL_WINDOW_SIZE).fill(0).map(() => new Float32Array(this.MEL_BINS).fill(1));
258
+ this.rawAudioRemainder = new Float32Array(0);
259
+ this.melContextBuffer.fill(0);
260
+ this.vadBuffer = [];
261
+ this.vadStateH.fill(0);
262
+ this.vadStateC.fill(0);
263
+ for (const name of this.embeddingBuffers.keys()) {
264
+ this.predictionBuffers.set(name, []);
265
+ const seeded = this.noiseSeededEmbeddings.get(name);
266
+ if (seeded) {
267
+ this.embeddingBuffers.set(name, seeded.map((e) => new Float32Array(e)));
268
+ } else {
269
+ this.embeddingBuffers.set(name, Array(this.EMBEDDING_WINDOW_SIZE).fill(0).map(() => new Float32Array(96).fill(0)));
270
+ }
271
+ }
272
+ }
273
+ };
274
+ // Annotate the CommonJS export names for ESM import in node:
275
+ 0 && (module.exports = {
276
+ Model
277
+ });
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Configuration options for the OpenWakeWord model.
3
+ */
4
+ interface ModelOptions {
5
+ /** Paths or URLs to the custom wake word ONNX models */
6
+ wakewordModels: string[];
7
+ /** Path or URL to the mel spectrogram ONNX model */
8
+ melspectrogramModelPath: string;
9
+ /** Path or URL to the embedding ONNX model */
10
+ embeddingModelPath: string;
11
+ /** Path or URL to the Silero VAD ONNX model (optional) */
12
+ vadModelPath?: string;
13
+ /** VAD threshold (0-1). 0 disables VAD. */
14
+ vadThreshold?: number;
15
+ /** Patience: How many consecutive frames above threshold before trigger */
16
+ patience?: Record<string, number>;
17
+ /** Thresholds for each model (required if patience or debounce is used) */
18
+ thresholds?: Record<string, number>;
19
+ /** Minimum time between detections in seconds */
20
+ debounceTime?: number;
21
+ /** Inference framework (only 'onnx' supported in this port) */
22
+ inferenceFramework: 'onnx';
23
+ /** Path to WASM files for onnxruntime-web if needed */
24
+ wasmPaths?: string;
25
+ }
26
+ /**
27
+ * Result of a prediction.
28
+ */
29
+ type PredictionResult = Record<string, number>;
30
+ /**
31
+ * OpenWakeWord Core Implementation in TypeScript.
32
+ */
33
+ declare class Model {
34
+ private options;
35
+ private melSession;
36
+ private embeddingSession;
37
+ private vadSession;
38
+ private customSessions;
39
+ private melBuffer;
40
+ private embeddingBuffers;
41
+ private predictionBuffers;
42
+ private vadBuffer;
43
+ private rawAudioRemainder;
44
+ private melContextBuffer;
45
+ private noiseSeededEmbeddings;
46
+ private readonly CHUNK_SIZE;
47
+ private readonly MEL_CONTEXT;
48
+ private readonly SAMPLE_RATE;
49
+ private readonly MEL_BINS;
50
+ private readonly FRAMES_PER_CHUNK;
51
+ private readonly MEL_WINDOW_SIZE;
52
+ private readonly EMBEDDING_WINDOW_SIZE;
53
+ private readonly MAX_MEL_FRAMES;
54
+ private readonly INITIAL_FRAMES_SUPPRESS;
55
+ private readonly PREDICTION_BUFFER_MAX;
56
+ private vadStateH;
57
+ private vadStateC;
58
+ private isLoaded;
59
+ constructor(options: ModelOptions);
60
+ init(): Promise<void>;
61
+ predict(audio: Float32Array | Int16Array): Promise<PredictionResult>;
62
+ private runMelSpectrogram;
63
+ private runEmbeddingModel;
64
+ private runClassifier;
65
+ private runVAD;
66
+ private extractModelName;
67
+ reset(): void;
68
+ }
69
+
70
+ export { Model, type ModelOptions, type PredictionResult };
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Configuration options for the OpenWakeWord model.
3
+ */
4
+ interface ModelOptions {
5
+ /** Paths or URLs to the custom wake word ONNX models */
6
+ wakewordModels: string[];
7
+ /** Path or URL to the mel spectrogram ONNX model */
8
+ melspectrogramModelPath: string;
9
+ /** Path or URL to the embedding ONNX model */
10
+ embeddingModelPath: string;
11
+ /** Path or URL to the Silero VAD ONNX model (optional) */
12
+ vadModelPath?: string;
13
+ /** VAD threshold (0-1). 0 disables VAD. */
14
+ vadThreshold?: number;
15
+ /** Patience: How many consecutive frames above threshold before trigger */
16
+ patience?: Record<string, number>;
17
+ /** Thresholds for each model (required if patience or debounce is used) */
18
+ thresholds?: Record<string, number>;
19
+ /** Minimum time between detections in seconds */
20
+ debounceTime?: number;
21
+ /** Inference framework (only 'onnx' supported in this port) */
22
+ inferenceFramework: 'onnx';
23
+ /** Path to WASM files for onnxruntime-web if needed */
24
+ wasmPaths?: string;
25
+ }
26
+ /**
27
+ * Result of a prediction.
28
+ */
29
+ type PredictionResult = Record<string, number>;
30
+ /**
31
+ * OpenWakeWord Core Implementation in TypeScript.
32
+ */
33
+ declare class Model {
34
+ private options;
35
+ private melSession;
36
+ private embeddingSession;
37
+ private vadSession;
38
+ private customSessions;
39
+ private melBuffer;
40
+ private embeddingBuffers;
41
+ private predictionBuffers;
42
+ private vadBuffer;
43
+ private rawAudioRemainder;
44
+ private melContextBuffer;
45
+ private noiseSeededEmbeddings;
46
+ private readonly CHUNK_SIZE;
47
+ private readonly MEL_CONTEXT;
48
+ private readonly SAMPLE_RATE;
49
+ private readonly MEL_BINS;
50
+ private readonly FRAMES_PER_CHUNK;
51
+ private readonly MEL_WINDOW_SIZE;
52
+ private readonly EMBEDDING_WINDOW_SIZE;
53
+ private readonly MAX_MEL_FRAMES;
54
+ private readonly INITIAL_FRAMES_SUPPRESS;
55
+ private readonly PREDICTION_BUFFER_MAX;
56
+ private vadStateH;
57
+ private vadStateC;
58
+ private isLoaded;
59
+ constructor(options: ModelOptions);
60
+ init(): Promise<void>;
61
+ predict(audio: Float32Array | Int16Array): Promise<PredictionResult>;
62
+ private runMelSpectrogram;
63
+ private runEmbeddingModel;
64
+ private runClassifier;
65
+ private runVAD;
66
+ private extractModelName;
67
+ reset(): void;
68
+ }
69
+
70
+ export { Model, type ModelOptions, type PredictionResult };
package/dist/index.js ADDED
@@ -0,0 +1,242 @@
1
+ // src/index.ts
2
+ import * as ort from "onnxruntime-web";
3
+ var Model = class {
4
+ constructor(options) {
5
+ this.options = options;
6
+ const runtime = ort.env ? ort : globalThis.ort;
7
+ if (runtime && options.wasmPaths) {
8
+ runtime.env.wasm.wasmPaths = options.wasmPaths;
9
+ }
10
+ this.melContextBuffer = new Float32Array(this.MEL_CONTEXT).fill(0);
11
+ }
12
+ melSession = null;
13
+ embeddingSession = null;
14
+ vadSession = null;
15
+ customSessions = /* @__PURE__ */ new Map();
16
+ // Buffers
17
+ melBuffer = [];
18
+ embeddingBuffers = /* @__PURE__ */ new Map();
19
+ predictionBuffers = /* @__PURE__ */ new Map();
20
+ vadBuffer = [];
21
+ rawAudioRemainder = new Float32Array(0);
22
+ melContextBuffer;
23
+ // Seeding history
24
+ noiseSeededEmbeddings = /* @__PURE__ */ new Map();
25
+ // Constants
26
+ CHUNK_SIZE = 1280;
27
+ MEL_CONTEXT = 480;
28
+ SAMPLE_RATE = 16e3;
29
+ MEL_BINS = 32;
30
+ FRAMES_PER_CHUNK = 8;
31
+ MEL_WINDOW_SIZE = 76;
32
+ EMBEDDING_WINDOW_SIZE = 24;
33
+ MAX_MEL_FRAMES = 970;
34
+ INITIAL_FRAMES_SUPPRESS = 5;
35
+ PREDICTION_BUFFER_MAX = 30;
36
+ // VAD State (Silero VAD)
37
+ vadStateH = new Float32Array(2 * 1 * 64).fill(0);
38
+ vadStateC = new Float32Array(2 * 1 * 64).fill(0);
39
+ isLoaded = false;
40
+ async init() {
41
+ try {
42
+ this.melSession = await ort.InferenceSession.create(this.options.melspectrogramModelPath);
43
+ this.embeddingSession = await ort.InferenceSession.create(this.options.embeddingModelPath);
44
+ if (this.options.vadModelPath && this.options.vadThreshold && this.options.vadThreshold > 0) {
45
+ this.vadSession = await ort.InferenceSession.create(this.options.vadModelPath);
46
+ }
47
+ this.melBuffer = Array(this.MEL_WINDOW_SIZE).fill(0).map(() => new Float32Array(this.MEL_BINS).fill(1));
48
+ const warmNoise = new Float32Array(this.SAMPLE_RATE * 4);
49
+ for (let i = 0; i < warmNoise.length; i++) warmNoise[i] = Math.random() * 2e3 - 1e3;
50
+ const tempMelContext = new Float32Array(this.MEL_CONTEXT).fill(0);
51
+ const generatedEmbeddings = [];
52
+ for (let i = 0; i <= warmNoise.length - this.CHUNK_SIZE; i += this.CHUNK_SIZE) {
53
+ const chunk = warmNoise.subarray(i, i + this.CHUNK_SIZE);
54
+ const melInput = new Float32Array(this.CHUNK_SIZE + this.MEL_CONTEXT);
55
+ melInput.set(tempMelContext);
56
+ melInput.set(chunk, this.MEL_CONTEXT);
57
+ tempMelContext.set(chunk.subarray(this.CHUNK_SIZE - this.MEL_CONTEXT));
58
+ const melOutput = await this.runMelSpectrogram(melInput);
59
+ for (let f = 0; f < this.FRAMES_PER_CHUNK; f++) {
60
+ const frame = new Float32Array(this.MEL_BINS);
61
+ for (let b = 0; b < this.MEL_BINS; b++) {
62
+ const idx = f * this.MEL_BINS + b;
63
+ frame[b] = melOutput[idx] / 10 + 2;
64
+ }
65
+ this.melBuffer.push(frame);
66
+ }
67
+ while (this.melBuffer.length > this.MAX_MEL_FRAMES) this.melBuffer.shift();
68
+ const emb = await this.runEmbeddingModel();
69
+ generatedEmbeddings.push(emb);
70
+ }
71
+ for (const modelPath of this.options.wakewordModels) {
72
+ const session = await ort.InferenceSession.create(modelPath);
73
+ const name = this.extractModelName(modelPath);
74
+ this.customSessions.set(name, session);
75
+ const history = generatedEmbeddings.slice(-this.EMBEDDING_WINDOW_SIZE).map((e) => new Float32Array(e));
76
+ this.noiseSeededEmbeddings.set(name, history);
77
+ this.embeddingBuffers.set(name, history.map((e) => new Float32Array(e)));
78
+ this.predictionBuffers.set(name, []);
79
+ }
80
+ this.isLoaded = true;
81
+ console.log("OpenWakeWord models loaded and bit-perfectly aligned");
82
+ } catch (error) {
83
+ console.error("Failed to initialize OpenWakeWord models:", error);
84
+ throw error;
85
+ }
86
+ }
87
+ async predict(audio) {
88
+ if (!this.isLoaded) throw new Error("Model not initialized");
89
+ let pcmAudio;
90
+ if (audio instanceof Int16Array) {
91
+ pcmAudio = new Float32Array(audio.length);
92
+ for (let i = 0; i < audio.length; i++) pcmAudio[i] = audio[i];
93
+ } else {
94
+ let max = 0;
95
+ for (let i = 0; i < Math.min(audio.length, 1e3); i++) {
96
+ const abs = Math.abs(audio[i]);
97
+ if (abs > max) max = abs;
98
+ }
99
+ if (max <= 1) {
100
+ pcmAudio = new Float32Array(audio.length);
101
+ for (let i = 0; i < audio.length; i++) pcmAudio[i] = audio[i] * 32768;
102
+ } else {
103
+ pcmAudio = audio;
104
+ }
105
+ }
106
+ let combinedAudio = new Float32Array(this.rawAudioRemainder.length + pcmAudio.length);
107
+ combinedAudio.set(this.rawAudioRemainder);
108
+ combinedAudio.set(pcmAudio, this.rawAudioRemainder.length);
109
+ const scores = {};
110
+ for (const name of this.customSessions.keys()) scores[name] = 0;
111
+ let offset = 0;
112
+ while (offset + this.CHUNK_SIZE <= combinedAudio.length) {
113
+ const chunk = combinedAudio.subarray(offset, offset + this.CHUNK_SIZE);
114
+ offset += this.CHUNK_SIZE;
115
+ const melInput = new Float32Array(this.CHUNK_SIZE + this.MEL_CONTEXT);
116
+ melInput.set(this.melContextBuffer);
117
+ melInput.set(chunk, this.MEL_CONTEXT);
118
+ this.melContextBuffer.set(chunk.subarray(this.CHUNK_SIZE - this.MEL_CONTEXT));
119
+ if (this.vadSession && this.options.vadThreshold) {
120
+ const vadScore = await this.runVAD(chunk);
121
+ this.vadBuffer.push(vadScore);
122
+ while (this.vadBuffer.length > 30) this.vadBuffer.shift();
123
+ }
124
+ const melOutput = await this.runMelSpectrogram(melInput);
125
+ for (let f = 0; f < this.FRAMES_PER_CHUNK; f++) {
126
+ const frame = new Float32Array(this.MEL_BINS);
127
+ for (let b = 0; b < this.MEL_BINS; b++) {
128
+ const idx = f * this.MEL_BINS + b;
129
+ frame[b] = melOutput[idx] / 10 + 2;
130
+ }
131
+ this.melBuffer.push(frame);
132
+ }
133
+ while (this.melBuffer.length > this.MAX_MEL_FRAMES) this.melBuffer.shift();
134
+ const embedding = await this.runEmbeddingModel();
135
+ for (const [name, session] of this.customSessions.entries()) {
136
+ const embBuf = this.embeddingBuffers.get(name);
137
+ embBuf.shift();
138
+ embBuf.push(embedding);
139
+ let score = await this.runClassifier(name, session);
140
+ if (this.vadSession && this.options.vadThreshold) {
141
+ const window = this.vadBuffer.slice(-7, -4);
142
+ const maxVAD = window.length > 0 ? Math.max(...window) : 0;
143
+ if (maxVAD < this.options.vadThreshold) score = 0;
144
+ }
145
+ const predBuf = this.predictionBuffers.get(name);
146
+ predBuf.push(score);
147
+ while (predBuf.length > this.PREDICTION_BUFFER_MAX) predBuf.shift();
148
+ if (predBuf.length < this.INITIAL_FRAMES_SUPPRESS) {
149
+ score = 0;
150
+ } else if (this.options.patience?.[name] || this.options.debounceTime && this.options.debounceTime > 0) {
151
+ const threshold = this.options.thresholds?.[name] ?? 0.5;
152
+ if (this.options.patience?.[name]) {
153
+ const p = this.options.patience[name];
154
+ const recentScores = predBuf.slice(-p);
155
+ const countAbove = recentScores.filter((s) => s >= threshold).length;
156
+ if (countAbove < p) score = 0;
157
+ } else if (this.options.debounceTime) {
158
+ const framesToWait = Math.ceil(this.options.debounceTime / 0.08);
159
+ const recentScores = predBuf.slice(-framesToWait - 1, -1);
160
+ const alreadyTriggered = recentScores.some((s) => s >= threshold);
161
+ if (score >= threshold && alreadyTriggered) score = 0;
162
+ }
163
+ }
164
+ scores[name] = Math.max(scores[name], score);
165
+ }
166
+ }
167
+ this.rawAudioRemainder = combinedAudio.slice(offset);
168
+ return scores;
169
+ }
170
+ async runMelSpectrogram(input) {
171
+ const inputTensor = new ort.Tensor("float32", input, [1, input.length]);
172
+ const results = await this.melSession.run({ [this.melSession.inputNames[0]]: inputTensor });
173
+ return results[this.melSession.outputNames[0]].data;
174
+ }
175
+ async runEmbeddingModel() {
176
+ const windowData = new Float32Array(this.MEL_WINDOW_SIZE * this.MEL_BINS);
177
+ const startIdx = this.melBuffer.length - this.MEL_WINDOW_SIZE;
178
+ for (let t = 0; t < this.MEL_WINDOW_SIZE; t++) {
179
+ windowData.set(this.melBuffer[startIdx + t], t * this.MEL_BINS);
180
+ }
181
+ const windowTensor = new ort.Tensor("float32", windowData, [1, this.MEL_WINDOW_SIZE, this.MEL_BINS, 1]);
182
+ const results = await this.embeddingSession.run({ [this.embeddingSession.inputNames[0]]: windowTensor });
183
+ const output = results[this.embeddingSession.outputNames[0]].data;
184
+ const embedding = new Float32Array(96);
185
+ for (let i = 0; i < 96; i++) {
186
+ let v = output[i] ?? 0;
187
+ if (isNaN(v) || !isFinite(v)) v = 0;
188
+ embedding[i] = v;
189
+ }
190
+ return embedding;
191
+ }
192
+ async runClassifier(name, session) {
193
+ const embBuf = this.embeddingBuffers.get(name);
194
+ const predData = new Float32Array(this.EMBEDDING_WINDOW_SIZE * 96);
195
+ for (let t = 0; t < this.EMBEDDING_WINDOW_SIZE; t++) predData.set(embBuf[t], t * 96);
196
+ const predTensor = new ort.Tensor("float32", predData, [1, this.EMBEDDING_WINDOW_SIZE, 96]);
197
+ const results = await session.run({ [session.inputNames[0]]: predTensor });
198
+ return results[session.outputNames[0]].data[0];
199
+ }
200
+ async runVAD(chunk) {
201
+ const normalized = new Float32Array(chunk.length);
202
+ for (let i = 0; i < chunk.length; i++) normalized[i] = chunk[i] / 32768;
203
+ const srTensor = new ort.Tensor("int64", BigInt64Array.from([BigInt(this.SAMPLE_RATE)]), [1]);
204
+ const hTensor = new ort.Tensor("float32", this.vadStateH, [2, 1, 64]);
205
+ const cTensor = new ort.Tensor("float32", this.vadStateC, [2, 1, 64]);
206
+ const inputTensor = new ort.Tensor("float32", normalized, [1, chunk.length]);
207
+ const feeds = {
208
+ [this.vadSession.inputNames[0]]: inputTensor,
209
+ [this.vadSession.inputNames[1]]: srTensor,
210
+ [this.vadSession.inputNames[2]]: hTensor,
211
+ [this.vadSession.inputNames[3]]: cTensor
212
+ };
213
+ const results = await this.vadSession.run(feeds);
214
+ this.vadStateH = results[this.vadSession.outputNames[1]].data;
215
+ this.vadStateC = results[this.vadSession.outputNames[2]].data;
216
+ return results[this.vadSession.outputNames[0]].data[0];
217
+ }
218
+ extractModelName(path) {
219
+ const base = path.split("/").pop() || path;
220
+ return base.replace(".onnx", "").replace(".tflite", "");
221
+ }
222
+ reset() {
223
+ this.melBuffer = Array(this.MEL_WINDOW_SIZE).fill(0).map(() => new Float32Array(this.MEL_BINS).fill(1));
224
+ this.rawAudioRemainder = new Float32Array(0);
225
+ this.melContextBuffer.fill(0);
226
+ this.vadBuffer = [];
227
+ this.vadStateH.fill(0);
228
+ this.vadStateC.fill(0);
229
+ for (const name of this.embeddingBuffers.keys()) {
230
+ this.predictionBuffers.set(name, []);
231
+ const seeded = this.noiseSeededEmbeddings.get(name);
232
+ if (seeded) {
233
+ this.embeddingBuffers.set(name, seeded.map((e) => new Float32Array(e)));
234
+ } else {
235
+ this.embeddingBuffers.set(name, Array(this.EMBEDDING_WINDOW_SIZE).fill(0).map(() => new Float32Array(96).fill(0)));
236
+ }
237
+ }
238
+ }
239
+ };
240
+ export {
241
+ Model
242
+ };
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "openwakeword-js",
3
+ "version": "0.1.0",
4
+ "description": "Port of openWakeWord to JavaScript/TypeScript using ONNX Runtime",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "type": "module",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.mjs",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "src",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "dependencies": {
23
+ "onnxruntime-web": "^1.19.0"
24
+ },
25
+ "devDependencies": {
26
+ "typescript": "^5.0.0",
27
+ "tsup": "^8.0.0"
28
+ },
29
+ "scripts": {
30
+ "build": "tsup src/index.ts --format esm,cjs --dts",
31
+ "dev": "tsup src/index.ts --format esm,cjs --watch --dts"
32
+ },
33
+ "keywords": [
34
+ "wakeword",
35
+ "keyword detection",
36
+ "audio",
37
+ "ml",
38
+ "onnx",
39
+ "javascript",
40
+ "browser"
41
+ ],
42
+ "homepage": "https://github.com/dscripka/openWakeWord",
43
+ "bugs": {
44
+ "url": "https://github.com/dscripka/openWakeWord/issues"
45
+ },
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "https://github.com/Firojpaudel/OpenWakeWord_npm_porting.git"
49
+ },
50
+ "author": "David Scripka (Original), Firojpaudel (JS Port)",
51
+ "license": "Apache-2.0"
52
+ }
package/src/index.ts ADDED
@@ -0,0 +1,316 @@
1
+ import * as ort from 'onnxruntime-web';
2
+
3
+ /**
4
+ * Configuration options for the OpenWakeWord model.
5
+ */
6
+ export interface ModelOptions {
7
+ /** Paths or URLs to the custom wake word ONNX models */
8
+ wakewordModels: string[];
9
+ /** Path or URL to the mel spectrogram ONNX model */
10
+ melspectrogramModelPath: string;
11
+ /** Path or URL to the embedding ONNX model */
12
+ embeddingModelPath: string;
13
+ /** Path or URL to the Silero VAD ONNX model (optional) */
14
+ vadModelPath?: string;
15
+ /** VAD threshold (0-1). 0 disables VAD. */
16
+ vadThreshold?: number;
17
+ /** Patience: How many consecutive frames above threshold before trigger */
18
+ patience?: Record<string, number>;
19
+ /** Thresholds for each model (required if patience or debounce is used) */
20
+ thresholds?: Record<string, number>;
21
+ /** Minimum time between detections in seconds */
22
+ debounceTime?: number;
23
+ /** Inference framework (only 'onnx' supported in this port) */
24
+ inferenceFramework: 'onnx';
25
+ /** Path to WASM files for onnxruntime-web if needed */
26
+ wasmPaths?: string;
27
+ }
28
+
29
+ /**
30
+ * Result of a prediction.
31
+ */
32
+ export type PredictionResult = Record<string, number>;
33
+
34
+ /**
35
+ * OpenWakeWord Core Implementation in TypeScript.
36
+ */
37
+ export class Model {
38
+ private melSession: ort.InferenceSession | null = null;
39
+ private embeddingSession: ort.InferenceSession | null = null;
40
+ private vadSession: ort.InferenceSession | null = null;
41
+ private customSessions: Map<string, ort.InferenceSession> = new Map();
42
+
43
+ // Buffers
44
+ private melBuffer: Float32Array[] = [];
45
+ private embeddingBuffers: Map<string, Float32Array[]> = new Map();
46
+ private predictionBuffers: Map<string, number[]> = new Map();
47
+ private vadBuffer: number[] = [];
48
+ private rawAudioRemainder: Float32Array = new Float32Array(0);
49
+ private melContextBuffer: Float32Array;
50
+
51
+ // Seeding history
52
+ private noiseSeededEmbeddings: Map<string, Float32Array[]> = new Map();
53
+
54
+ // Constants
55
+ private readonly CHUNK_SIZE = 1280;
56
+ private readonly MEL_CONTEXT = 480;
57
+ private readonly SAMPLE_RATE = 16000;
58
+ private readonly MEL_BINS = 32;
59
+ private readonly FRAMES_PER_CHUNK = 8;
60
+ private readonly MEL_WINDOW_SIZE = 76;
61
+ private readonly EMBEDDING_WINDOW_SIZE = 24;
62
+ private readonly MAX_MEL_FRAMES = 970;
63
+ private readonly INITIAL_FRAMES_SUPPRESS = 5;
64
+ private readonly PREDICTION_BUFFER_MAX = 30;
65
+
66
+ // VAD State (Silero VAD)
67
+ private vadStateH = new Float32Array(2 * 1 * 64).fill(0);
68
+ private vadStateC = new Float32Array(2 * 1 * 64).fill(0);
69
+
70
+ private isLoaded = false;
71
+
72
+ constructor(private options: ModelOptions) {
73
+ // Handle environments where 'ort' might be a global (some browser setups)
74
+ const runtime = (ort as any).env ? ort : (globalThis as any).ort;
75
+ if (runtime && options.wasmPaths) {
76
+ runtime.env.wasm.wasmPaths = options.wasmPaths;
77
+ }
78
+ this.melContextBuffer = new Float32Array(this.MEL_CONTEXT).fill(0);
79
+ }
80
+
81
+ async init() {
82
+ try {
83
+ this.melSession = await ort.InferenceSession.create(this.options.melspectrogramModelPath);
84
+ this.embeddingSession = await ort.InferenceSession.create(this.options.embeddingModelPath);
85
+
86
+ if (this.options.vadModelPath && this.options.vadThreshold && this.options.vadThreshold > 0) {
87
+ this.vadSession = await ort.InferenceSession.create(this.options.vadModelPath);
88
+ }
89
+
90
+ // 1. Initialize Mel buffer with ones as in Python
91
+ this.melBuffer = Array(this.MEL_WINDOW_SIZE).fill(0).map(() => new Float32Array(this.MEL_BINS).fill(1.0));
92
+
93
+ // 2. Generate noise-seeded history for parity
94
+ const warmNoise = new Float32Array(this.SAMPLE_RATE * 4);
95
+ for (let i = 0; i < warmNoise.length; i++) warmNoise[i] = (Math.random() * 2000 - 1000);
96
+
97
+ const tempMelContext = new Float32Array(this.MEL_CONTEXT).fill(0);
98
+ const generatedEmbeddings: Float32Array[] = [];
99
+
100
+ for (let i = 0; i <= warmNoise.length - this.CHUNK_SIZE; i += this.CHUNK_SIZE) {
101
+ const chunk = warmNoise.subarray(i, i + this.CHUNK_SIZE);
102
+ const melInput = new Float32Array(this.CHUNK_SIZE + this.MEL_CONTEXT);
103
+ melInput.set(tempMelContext);
104
+ melInput.set(chunk, this.MEL_CONTEXT);
105
+ tempMelContext.set(chunk.subarray(this.CHUNK_SIZE - this.MEL_CONTEXT));
106
+
107
+ const melOutput = await this.runMelSpectrogram(melInput);
108
+ for (let f = 0; f < this.FRAMES_PER_CHUNK; f++) {
109
+ const frame = new Float32Array(this.MEL_BINS);
110
+ for (let b = 0; b < this.MEL_BINS; b++) {
111
+ const idx = f * this.MEL_BINS + b;
112
+ frame[b] = melOutput[idx] / 10.0 + 2.0;
113
+ }
114
+ this.melBuffer.push(frame);
115
+ }
116
+ while (this.melBuffer.length > this.MAX_MEL_FRAMES) this.melBuffer.shift();
117
+
118
+ const emb = await this.runEmbeddingModel();
119
+ generatedEmbeddings.push(emb);
120
+ }
121
+
122
+ for (const modelPath of this.options.wakewordModels) {
123
+ const session = await ort.InferenceSession.create(modelPath);
124
+ const name = this.extractModelName(modelPath);
125
+ this.customSessions.set(name, session);
126
+
127
+ // Store seeded history to be used during initial prediction and resets
128
+ const history = generatedEmbeddings.slice(-this.EMBEDDING_WINDOW_SIZE).map(e => new Float32Array(e));
129
+ this.noiseSeededEmbeddings.set(name, history);
130
+ this.embeddingBuffers.set(name, history.map(e => new Float32Array(e)));
131
+ this.predictionBuffers.set(name, []);
132
+ }
133
+
134
+ // Final sync: don't call reset() here as it would wipe what we just did
135
+ this.isLoaded = true;
136
+ console.log('OpenWakeWord models loaded and bit-perfectly aligned');
137
+ } catch (error) {
138
+ console.error('Failed to initialize OpenWakeWord models:', error);
139
+ throw error;
140
+ }
141
+ }
142
+
143
+ async predict(audio: Float32Array | Int16Array): Promise<PredictionResult> {
144
+ if (!this.isLoaded) throw new Error('Model not initialized');
145
+
146
+ let pcmAudio: Float32Array;
147
+ if (audio instanceof Int16Array) {
148
+ pcmAudio = new Float32Array(audio.length);
149
+ for (let i = 0; i < audio.length; i++) pcmAudio[i] = audio[i];
150
+ } else {
151
+ let max = 0;
152
+ for (let i = 0; i < Math.min(audio.length, 1000); i++) {
153
+ const abs = Math.abs(audio[i]);
154
+ if (abs > max) max = abs;
155
+ }
156
+ if (max <= 1.0) {
157
+ pcmAudio = new Float32Array(audio.length);
158
+ for (let i = 0; i < audio.length; i++) pcmAudio[i] = audio[i] * 32768.0;
159
+ } else {
160
+ pcmAudio = audio;
161
+ }
162
+ }
163
+
164
+ let combinedAudio = new Float32Array(this.rawAudioRemainder.length + pcmAudio.length);
165
+ combinedAudio.set(this.rawAudioRemainder);
166
+ combinedAudio.set(pcmAudio, this.rawAudioRemainder.length);
167
+
168
+ const scores: PredictionResult = {};
169
+ for (const name of this.customSessions.keys()) scores[name] = 0.0;
170
+
171
+ let offset = 0;
172
+ while (offset + this.CHUNK_SIZE <= combinedAudio.length) {
173
+ const chunk = combinedAudio.subarray(offset, offset + this.CHUNK_SIZE);
174
+ offset += this.CHUNK_SIZE;
175
+
176
+ // PRECISE SLIDING WINDOW: 1280 new samples + 480 context samples
177
+ const melInput = new Float32Array(this.CHUNK_SIZE + this.MEL_CONTEXT);
178
+ melInput.set(this.melContextBuffer);
179
+ melInput.set(chunk, this.MEL_CONTEXT);
180
+ this.melContextBuffer.set(chunk.subarray(this.CHUNK_SIZE - this.MEL_CONTEXT));
181
+
182
+ if (this.vadSession && this.options.vadThreshold) {
183
+ const vadScore = await this.runVAD(chunk);
184
+ this.vadBuffer.push(vadScore);
185
+ while (this.vadBuffer.length > 30) this.vadBuffer.shift();
186
+ }
187
+
188
+ const melOutput = await this.runMelSpectrogram(melInput);
189
+ for (let f = 0; f < this.FRAMES_PER_CHUNK; f++) {
190
+ const frame = new Float32Array(this.MEL_BINS);
191
+ for (let b = 0; b < this.MEL_BINS; b++) {
192
+ const idx = f * this.MEL_BINS + b;
193
+ frame[b] = melOutput[idx] / 10.0 + 2.0;
194
+ }
195
+ this.melBuffer.push(frame);
196
+ }
197
+ while (this.melBuffer.length > this.MAX_MEL_FRAMES) this.melBuffer.shift();
198
+
199
+ const embedding = await this.runEmbeddingModel();
200
+ for (const [name, session] of this.customSessions.entries()) {
201
+ const embBuf = this.embeddingBuffers.get(name)!;
202
+ embBuf.shift();
203
+ embBuf.push(embedding);
204
+
205
+ let score = await this.runClassifier(name, session);
206
+
207
+ if (this.vadSession && this.options.vadThreshold) {
208
+ const window = this.vadBuffer.slice(-7, -4);
209
+ const maxVAD = window.length > 0 ? Math.max(...window) : 0;
210
+ if (maxVAD < this.options.vadThreshold) score = 0.0;
211
+ }
212
+
213
+ const predBuf = this.predictionBuffers.get(name)!;
214
+ predBuf.push(score);
215
+ while (predBuf.length > this.PREDICTION_BUFFER_MAX) predBuf.shift();
216
+
217
+ if (predBuf.length < this.INITIAL_FRAMES_SUPPRESS) {
218
+ score = 0.0;
219
+ } else if (this.options.patience?.[name] || (this.options.debounceTime && this.options.debounceTime > 0)) {
220
+ const threshold = this.options.thresholds?.[name] ?? 0.5;
221
+ if (this.options.patience?.[name]) {
222
+ const p = this.options.patience[name];
223
+ const recentScores = predBuf.slice(-p);
224
+ const countAbove = recentScores.filter(s => s >= threshold).length;
225
+ if (countAbove < p) score = 0.0;
226
+ } else if (this.options.debounceTime) {
227
+ const framesToWait = Math.ceil(this.options.debounceTime / 0.08);
228
+ const recentScores = predBuf.slice(-framesToWait - 1, -1);
229
+ const alreadyTriggered = recentScores.some(s => s >= threshold);
230
+ if (score >= threshold && alreadyTriggered) score = 0.0;
231
+ }
232
+ }
233
+ scores[name] = Math.max(scores[name], score);
234
+ }
235
+ }
236
+
237
+ this.rawAudioRemainder = combinedAudio.slice(offset);
238
+ return scores;
239
+ }
240
+
241
+ private async runMelSpectrogram(input: Float32Array): Promise<Float32Array> {
242
+ const inputTensor = new ort.Tensor('float32', input, [1, input.length]);
243
+ const results = await this.melSession!.run({ [this.melSession!.inputNames[0]]: inputTensor });
244
+ return results[this.melSession!.outputNames[0]].data as Float32Array;
245
+ }
246
+
247
+ private async runEmbeddingModel(): Promise<Float32Array> {
248
+ const windowData = new Float32Array(this.MEL_WINDOW_SIZE * this.MEL_BINS);
249
+ const startIdx = this.melBuffer.length - this.MEL_WINDOW_SIZE;
250
+ for (let t = 0; t < this.MEL_WINDOW_SIZE; t++) {
251
+ windowData.set(this.melBuffer[startIdx + t], t * this.MEL_BINS);
252
+ }
253
+ const windowTensor = new ort.Tensor('float32', windowData, [1, this.MEL_WINDOW_SIZE, this.MEL_BINS, 1]);
254
+ const results = await this.embeddingSession!.run({ [this.embeddingSession!.inputNames[0]]: windowTensor });
255
+ const output = results[this.embeddingSession!.outputNames[0]].data as Float32Array;
256
+ const embedding = new Float32Array(96);
257
+ for (let i = 0; i < 96; i++) {
258
+ let v = output[i] ?? 0;
259
+ if (isNaN(v) || !isFinite(v)) v = 0;
260
+ embedding[i] = v;
261
+ }
262
+ return embedding;
263
+ }
264
+
265
+ private async runClassifier(name: string, session: ort.InferenceSession): Promise<number> {
266
+ const embBuf = this.embeddingBuffers.get(name)!;
267
+ const predData = new Float32Array(this.EMBEDDING_WINDOW_SIZE * 96);
268
+ for (let t = 0; t < this.EMBEDDING_WINDOW_SIZE; t++) predData.set(embBuf[t], t * 96);
269
+ const predTensor = new ort.Tensor('float32', predData, [1, this.EMBEDDING_WINDOW_SIZE, 96]);
270
+ const results = await session.run({ [session.inputNames[0]]: predTensor });
271
+ return results[session.outputNames[0]].data[0] as number;
272
+ }
273
+
274
+ private async runVAD(chunk: Float32Array): Promise<number> {
275
+ const normalized = new Float32Array(chunk.length);
276
+ for (let i = 0; i < chunk.length; i++) normalized[i] = chunk[i] / 32768.0;
277
+ const srTensor = new ort.Tensor('int64', BigInt64Array.from([BigInt(this.SAMPLE_RATE)]), [1]);
278
+ const hTensor = new ort.Tensor('float32', this.vadStateH, [2, 1, 64]);
279
+ const cTensor = new ort.Tensor('float32', this.vadStateC, [2, 1, 64]);
280
+ const inputTensor = new ort.Tensor('float32', normalized, [1, chunk.length]);
281
+ const feeds = {
282
+ [this.vadSession!.inputNames[0]]: inputTensor,
283
+ [this.vadSession!.inputNames[1]]: srTensor,
284
+ [this.vadSession!.inputNames[2]]: hTensor,
285
+ [this.vadSession!.inputNames[3]]: cTensor
286
+ };
287
+
288
+ const results = await this.vadSession!.run(feeds);
289
+ this.vadStateH = results[this.vadSession!.outputNames[1]].data as any;
290
+ this.vadStateC = results[this.vadSession!.outputNames[2]].data as any;
291
+ return results[this.vadSession!.outputNames[0]].data[0] as number;
292
+ }
293
+
294
+ private extractModelName(path: string): string {
295
+ const base = path.split('/').pop() || path;
296
+ return base.replace('.onnx', '').replace('.tflite', '');
297
+ }
298
+
299
+ reset() {
300
+ this.melBuffer = Array(this.MEL_WINDOW_SIZE).fill(0).map(() => new Float32Array(this.MEL_BINS).fill(1.0));
301
+ this.rawAudioRemainder = new Float32Array(0);
302
+ this.melContextBuffer.fill(0);
303
+ this.vadBuffer = [];
304
+ this.vadStateH.fill(0);
305
+ this.vadStateC.fill(0);
306
+ for (const name of this.embeddingBuffers.keys()) {
307
+ this.predictionBuffers.set(name, []);
308
+ const seeded = this.noiseSeededEmbeddings.get(name);
309
+ if (seeded) {
310
+ this.embeddingBuffers.set(name, seeded.map(e => new Float32Array(e)));
311
+ } else {
312
+ this.embeddingBuffers.set(name, Array(this.EMBEDDING_WINDOW_SIZE).fill(0).map(() => new Float32Array(96).fill(0)));
313
+ }
314
+ }
315
+ }
316
+ }