kiwina commited on
Commit
6c15bad
·
verified ·
1 Parent(s): 0f665a5

Phonlet Wake lab from release v0.1.0

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ wake/model.pwake filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,10 +1,31 @@
1
  ---
2
- title: Wake
3
- emoji: 😻
4
- colorFrom: blue
5
- colorTo: yellow
6
  sdk: static
7
- pinned: false
 
 
 
 
 
 
 
 
 
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Phonlet Wake
3
+ emoji: 🎙️
4
+ colorFrom: red
5
+ colorTo: gray
6
  sdk: static
7
+ app_file: index.html
8
+ pinned: true
9
+ license: other
10
+ short_description: Type any wake word, hear it detected live in your browser
11
+ tags:
12
+ - wake-word
13
+ - keyword-spotting
14
+ - hotword
15
+ - webassembly
16
+ - on-device
17
+ models:
18
+ - phonletai/wake-en-1
19
  ---
20
 
21
+ # Phonlet Wake lab
22
+
23
+ Type any phrase: the threshold generator calibrates it in your browser (WebAssembly), and the
24
+ Phonlet Wake engine listens for it on your microphone with the 1 MB `en-1` model. Audio never
25
+ leaves the tab. Download the keyword file and use it with any Phonlet Wake SDK.
26
+
27
+ Model: [phonletai/wake-en-1](https://huggingface.co/phonletai/wake-en-1) · Source and SDKs:
28
+ [phonlet-ai/wake](https://github.com/phonlet-ai/wake) · Website: [phonletai.com](https://phonletai.com)
29
+
30
+ Built from `packaging/huggingface/space/` in the wake repository; the engine, model and generator
31
+ are the files of Phonlet Wake release v0.1.0. Licence: PolyForm Noncommercial 1.0.0.
app.mjs ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Phonlet Wake lab: type a phrase, calibrate it with the threshold generator (WebAssembly, in a
2
+ // worker), and listen for it with the browser SDK. The model, the SDK and the generator are the
3
+ // files of the Phonlet Wake release, served next to this page. Nothing leaves the tab.
4
+ import { WakeManager } from './wake/capture.mjs';
5
+
6
+ const MODEL = './wake/model.pwake';
7
+ const KEYWORDS = './wake/keywords.json';
8
+ const MAX_HEARD = 12;
9
+
10
+ // The engine's phone inventory: id i is PHONES[i] (0 is the blank).
11
+ // prettier-ignore
12
+ const PHONES = [
13
+ 'blank', 'AA', 'AE', 'AH', 'AO', 'AW', 'AY', 'B', 'CH', 'D', 'DH', 'EH', 'ER', 'EY', 'F', 'G',
14
+ 'HH', 'IH', 'IY', 'JH', 'K', 'L', 'M', 'N', 'NG', 'OW', 'OY', 'P', 'R', 'S', 'SH', 'T', 'TH',
15
+ 'UH', 'UW', 'V', 'W', 'Y', 'Z', 'ZH',
16
+ ];
17
+ const SOURCES = { lexicon: 'dictionary', g2p: 'predicted', explicit: 'your sounds' };
18
+
19
+ const $ = (id) => document.getElementById(id);
20
+ const ui = {
21
+ form: $('add'),
22
+ phrase: $('phrase'),
23
+ add: $('add-button'),
24
+ phrases: $('phrases'),
25
+ sensitivity: $('sensitivity'),
26
+ sensitivityValue: $('sensitivity-value'),
27
+ rate: $('rate'),
28
+ listen: $('listen'),
29
+ download: $('download'),
30
+ level: $('level'),
31
+ status: $('status'),
32
+ heard: $('heard'),
33
+ heardCount: $('heard-count'),
34
+ burst: $('burst'),
35
+ };
36
+
37
+ const state = {
38
+ model: null, // {id, sha256} of the keyword file the page started with
39
+ phrases: [], // {entry, source, fresh}
40
+ sensitivity: 0.5,
41
+ session: null, // {manager, context, stream, analyser, frame}
42
+ starting: false,
43
+ busy: false,
44
+ heard: 0,
45
+ };
46
+
47
+ const spell = (ids) => ids.map((id) => PHONES[id] ?? '?').join(' ');
48
+ const megabytes = (bytes) => (bytes / 1048576).toFixed(1);
49
+
50
+ function say(message, error = false) {
51
+ ui.status.textContent = message;
52
+ ui.status.classList.toggle('is-error', error);
53
+ }
54
+
55
+ function keywordFile() {
56
+ return {
57
+ model: state.model,
58
+ keywords: state.phrases.map((p) => p.entry),
59
+ metadata: {},
60
+ };
61
+ }
62
+
63
+ function render() {
64
+ ui.phrases.replaceChildren(
65
+ ...state.phrases.map((phrase, index) => {
66
+ const item = document.createElement('li');
67
+ if (phrase.fresh) item.classList.add('is-new');
68
+ const name = document.createElement('span');
69
+ name.className = 'name';
70
+ name.textContent = phrase.entry.name;
71
+ const sounds = document.createElement('span');
72
+ sounds.className = 'sounds';
73
+ sounds.textContent = spell(phrase.entry.pronunciations[0] ?? []);
74
+ const tag = document.createElement('span');
75
+ const warned = (phrase.entry.metadata?.warnings ?? []).length > 0;
76
+ tag.className = warned ? 'tag warn' : 'tag';
77
+ tag.textContent = warned ? 'check it' : (SOURCES[phrase.source] ?? 'built-in');
78
+ if (warned) tag.title = phrase.entry.metadata.warnings[0].message;
79
+ const remove = document.createElement('button');
80
+ remove.type = 'button';
81
+ remove.textContent = '×';
82
+ remove.setAttribute('aria-label', `Remove “${phrase.entry.name}”`);
83
+ remove.addEventListener('click', () => removePhrase(index));
84
+ item.append(name, sounds, tag, remove);
85
+ return item;
86
+ }),
87
+ );
88
+ const listening = Boolean(state.session);
89
+ ui.listen.textContent = listening ? 'Stop listening' : 'Start listening';
90
+ ui.listen.classList.toggle('is-on', listening);
91
+ ui.listen.disabled = state.starting || (!listening && state.phrases.length === 0);
92
+ ui.download.disabled = state.phrases.length === 0;
93
+ ui.add.disabled = state.busy;
94
+ }
95
+
96
+ // ---------- The threshold generator ----------
97
+ let worker = null;
98
+ let sequence = 0;
99
+ const pending = new Map();
100
+
101
+ function generate(request) {
102
+ if (!worker) {
103
+ worker = new Worker('./generator/worker.js');
104
+ worker.onmessage = ({ data }) => {
105
+ if (data.progress) {
106
+ const [loaded, total] = data.progress;
107
+ say(`Loading the calibrator · ${megabytes(loaded)} of ${megabytes(total)} MB, once`);
108
+ return;
109
+ }
110
+ const done = pending.get(data.id);
111
+ pending.delete(data.id);
112
+ done?.(data);
113
+ };
114
+ worker.onerror = (event) => {
115
+ for (const done of pending.values()) done({ error: event.message || 'generator failed' });
116
+ pending.clear();
117
+ worker?.terminate();
118
+ worker = null;
119
+ };
120
+ }
121
+ const id = ++sequence;
122
+ return new Promise((resolve, reject) => {
123
+ pending.set(id, (reply) => {
124
+ if (reply.error) reject(new Error(reply.error));
125
+ else if (reply.result?.error) reject(new Error(reply.result.error));
126
+ else resolve(reply.result);
127
+ });
128
+ worker.postMessage({ id, request });
129
+ });
130
+ }
131
+
132
+ async function addPhrase(text) {
133
+ const phrase = text.trim().replace(/\s+/g, ' ');
134
+ if (!phrase || state.busy) return;
135
+ const name = phrase.split('=')[0].trim().toLowerCase();
136
+ if (state.phrases.some((p) => p.entry.name.toLowerCase() === name)) {
137
+ say(`“${name}” is already in the list.`);
138
+ return;
139
+ }
140
+ state.busy = true;
141
+ render();
142
+ say(`Calibrating “${name}”…`);
143
+ try {
144
+ const result = await generate({ command: 'enroll', phrases: [phrase] });
145
+ if (result.model?.sha256 !== state.model.sha256) throw new Error('the generator is for another model');
146
+ const entry = result.keywords?.[0];
147
+ if (!entry) {
148
+ say(result.metadata?.unknown?.[0]?.error ?? `“${name}” could not be calibrated.`, true);
149
+ return;
150
+ }
151
+ state.phrases.forEach((p) => (p.fresh = false));
152
+ state.phrases.push({ entry, source: entry.metadata?.source, fresh: true });
153
+ ui.phrase.value = '';
154
+ const warning = entry.metadata?.warnings?.[0]?.message;
155
+ const listening = Boolean(state.session);
156
+ if (listening) await restart();
157
+ if (!state.session && listening) return; // restart failed and said why
158
+ say(
159
+ warning
160
+ ? `Added “${entry.name}”: ${warning}.`
161
+ : `Added “${entry.name}”. ${state.session ? 'Say it.' : 'Start listening and say it.'}`,
162
+ );
163
+ } catch (error) {
164
+ say(`Could not calibrate “${name}”: ${error.message}`, true);
165
+ } finally {
166
+ state.busy = false;
167
+ render();
168
+ }
169
+ }
170
+
171
+ async function removePhrase(index) {
172
+ const [removed] = state.phrases.splice(index, 1);
173
+ say(`Removed “${removed.entry.name}”.`);
174
+ if (state.session) {
175
+ if (state.phrases.length) await restart();
176
+ else await stop('Stopped: there are no phrases left.');
177
+ }
178
+ render();
179
+ }
180
+
181
+ // ---------- Listening ----------
182
+ const supportsSimd = () => {
183
+ try {
184
+ // A minimal module that returns a v128 constant.
185
+ return WebAssembly.validate(
186
+ new Uint8Array([
187
+ 0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 22, 1, 20, 0, 253, 12,
188
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11,
189
+ ]),
190
+ );
191
+ } catch {
192
+ return false;
193
+ }
194
+ };
195
+
196
+ async function start() {
197
+ if (state.session || state.starting || !state.phrases.length) return;
198
+ state.starting = true;
199
+ render();
200
+ say('Starting the engine…');
201
+ let context;
202
+ let stream;
203
+ try {
204
+ context = new AudioContext({ sampleRate: 16000 });
205
+ stream = await navigator.mediaDevices.getUserMedia({
206
+ audio: { channelCount: 1, echoCancellation: false, noiseSuppression: false, autoGainControl: false },
207
+ });
208
+ const analyser = context.createAnalyser();
209
+ analyser.fftSize = 1024;
210
+ context.createMediaStreamSource(stream).connect(analyser);
211
+ const manager = new WakeManager({
212
+ wake: { model: MODEL, keywords: keywordFile(), sensitivity: state.sensitivity, simd: supportsSimd() },
213
+ audioContext: context,
214
+ stream,
215
+ onDetection: heard,
216
+ onError: (error) => void stop(`Stopped: ${error.message}`, true),
217
+ });
218
+ const session = { manager, context, stream, analyser, frame: 0 };
219
+ state.session = session;
220
+ await manager.start();
221
+ const samples = new Float32Array(analyser.fftSize);
222
+ let level = 0;
223
+ const tick = () => {
224
+ analyser.getFloatTimeDomainData(samples);
225
+ let sum = 0;
226
+ for (const s of samples) sum += s * s;
227
+ const rms = Math.sqrt(sum / samples.length);
228
+ // -60 to -12 dBFS onto 0..1, so room noise stays low and speech fills the range.
229
+ const target = rms > 0.001 ? Math.min(1, Math.max(0, (20 * Math.log10(rms) + 60) / 48)) : 0;
230
+ level += (target - level) * 0.3;
231
+ ui.level.style.width = `${(level * 100).toFixed(1)}%`;
232
+ session.frame = requestAnimationFrame(tick);
233
+ };
234
+ session.frame = requestAnimationFrame(tick);
235
+ const names = state.phrases.slice(0, 3).map((p) => `“${p.entry.name}”`);
236
+ say(`Listening. Say ${names.join(', ')}${state.phrases.length > 3 ? '…' : '.'}`);
237
+ } catch (error) {
238
+ const owned = state.session;
239
+ state.session = null;
240
+ await owned?.manager.close().catch(() => {});
241
+ stream?.getTracks().forEach((track) => track.stop());
242
+ await context?.close().catch(() => {});
243
+ const message =
244
+ error?.name === 'NotAllowedError'
245
+ ? 'Microphone access was blocked. Allow it in the address bar and try again.'
246
+ : error?.name === 'NotSupportedError'
247
+ ? 'This browser cannot record at 16 kHz. Try Chrome or Edge.'
248
+ : (error?.message ?? String(error));
249
+ say(message, true);
250
+ } finally {
251
+ state.starting = false;
252
+ render();
253
+ }
254
+ }
255
+
256
+ async function stop(message = 'Stopped. The microphone is released.', error = false) {
257
+ const session = state.session;
258
+ state.session = null;
259
+ if (session) {
260
+ cancelAnimationFrame(session.frame);
261
+ await session.manager.close().catch(() => {});
262
+ session.stream.getTracks().forEach((track) => track.stop());
263
+ await session.context.close().catch(() => {});
264
+ }
265
+ ui.level.style.width = '0%';
266
+ say(message, error);
267
+ render();
268
+ }
269
+
270
+ async function restart() {
271
+ await stop('Restarting with the new phrases…');
272
+ await start();
273
+ }
274
+
275
+ function heard(event) {
276
+ state.heard += 1;
277
+ ui.heardCount.textContent = String(state.heard);
278
+ const item = document.createElement('li');
279
+ const name = document.createElement('span');
280
+ name.textContent = event.keyword;
281
+ const time = document.createElement('time');
282
+ const now = new Date();
283
+ time.dateTime = now.toISOString();
284
+ time.textContent = now.toLocaleTimeString();
285
+ item.append(name, time);
286
+ ui.heard.prepend(item);
287
+ while (ui.heard.children.length > MAX_HEARD) ui.heard.lastElementChild.remove();
288
+ ui.burst.textContent = `“${event.keyword}”`;
289
+ ui.burst.classList.remove('is-on');
290
+ void ui.burst.offsetWidth; // restart the animation
291
+ ui.burst.classList.add('is-on');
292
+ }
293
+
294
+ // ---------- Controls ----------
295
+ function describeSensitivity(value) {
296
+ // Sensitivity 0 aims at 0.1 false alarms per hour of speech, 1 at 10, log-linear between.
297
+ const rate = 0.1 * 100 ** value;
298
+ const shown = rate < 1 ? rate.toFixed(1) : rate < 10 ? rate.toFixed(1).replace(/\.0$/, '') : rate.toFixed(0);
299
+ return `Aims at about ${shown} false alarm${shown === '1' ? '' : 's'} per hour of speech.`;
300
+ }
301
+
302
+ ui.form.addEventListener('submit', (event) => {
303
+ event.preventDefault();
304
+ void addPhrase(ui.phrase.value);
305
+ });
306
+ ui.sensitivity.addEventListener('input', () => {
307
+ state.sensitivity = Number(ui.sensitivity.value);
308
+ ui.sensitivityValue.textContent = state.sensitivity.toFixed(2);
309
+ ui.rate.textContent = describeSensitivity(state.sensitivity);
310
+ });
311
+ ui.sensitivity.addEventListener('change', () => {
312
+ if (state.session) void restart();
313
+ });
314
+ ui.listen.addEventListener('click', () => void (state.session ? stop() : start()));
315
+ ui.download.addEventListener('click', () => {
316
+ const blob = new Blob([JSON.stringify(keywordFile(), null, 2) + '\n'], { type: 'application/json' });
317
+ const url = URL.createObjectURL(blob);
318
+ const link = document.createElement('a');
319
+ link.href = url;
320
+ link.download = 'keywords.json';
321
+ document.body.append(link);
322
+ link.click();
323
+ link.remove();
324
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
325
+ say('Downloaded keywords.json: use it with any Phonlet Wake SDK and the en-1 model.');
326
+ });
327
+ window.addEventListener('pagehide', () => void stop());
328
+
329
+ try {
330
+ const response = await fetch(KEYWORDS);
331
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
332
+ const file = await response.json();
333
+ state.model = file.model;
334
+ state.phrases = file.keywords.map((entry) => ({ entry, source: entry.metadata?.source }));
335
+ say('Type any phrase and press Enter, or start listening for the phrases below.');
336
+ } catch (error) {
337
+ say(`Could not load the phrases: ${error.message}`, true);
338
+ }
339
+ ui.rate.textContent = describeSensitivity(state.sensitivity);
340
+ render();
generator/LICENSE ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Required Notice: Copyright 2026 Phonlet AI (https://phonletai.com)
2
+
3
+ # PolyForm Noncommercial License 1.0.0
4
+
5
+ <https://polyformproject.org/licenses/noncommercial/1.0.0>
6
+
7
+ ## Acceptance
8
+
9
+ In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
10
+
11
+ ## Copyright License
12
+
13
+ The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
14
+
15
+ ## Distribution License
16
+
17
+ The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
18
+
19
+ ## Notices
20
+
21
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
22
+
23
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
24
+
25
+ ## Changes and New Works License
26
+
27
+ The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
28
+
29
+ ## Patent License
30
+
31
+ The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
32
+
33
+ ## Noncommercial Purposes
34
+
35
+ Any noncommercial purpose is a permitted purpose.
36
+
37
+ ## Personal Uses
38
+
39
+ Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose.
40
+
41
+ ## Noncommercial Organizations
42
+
43
+ Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding.
44
+
45
+ ## Fair Use
46
+
47
+ You may have "fair use" rights for the software under the law. These terms do not limit them.
48
+
49
+ ## No Other Rights
50
+
51
+ These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
52
+
53
+ ## Patent Defense
54
+
55
+ If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
56
+
57
+ ## Violations
58
+
59
+ The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
60
+
61
+ ## No Liability
62
+
63
+ ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
64
+
65
+ ## Definitions
66
+
67
+ The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
68
+
69
+ **You** refers to the individual or entity agreeing to these terms.
70
+
71
+ **Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
72
+
73
+ **Your licenses** are all the licenses granted to you for the software under these terms.
74
+
75
+ **Use** means anything you do with the software requiring one of your licenses.
generator/THIRD_PARTY_NOTICES.md ADDED
@@ -0,0 +1,684 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Third-party notices
2
+
3
+ `wake-threshold` (this source, the Linux, Windows and macOS binaries and the WebAssembly module) is
4
+ Copyright 2026 Phonlet AI and licensed under the PolyForm Noncommercial License 1.0.0, in the file
5
+ `LICENSE`. Commercial licences: `COMMERCIAL.md`, or contact@phonletai.com. The binaries and the
6
+ WebAssembly module contain the third-party work below; its terms and the credit each part asks for
7
+ follow. Ship this file with every copy of a binary or the module.
8
+
9
+ ## Embedded data and models
10
+
11
+ | Part | Licence | Credit |
12
+ | --- | --- | --- |
13
+ | g2p_en 2.1.0: the GRU model weights (`assets/g2p/checkpoint20.npz`) and the homograph list (`assets/g2p/homographs.en`), unchanged, and its prediction procedure, rewritten in Rust by Phonlet AI (`src/g2p.rs`); `assets/g2p/homograph_oov.json` records g2p_en's output for three words | Apache-2.0 (text below) | Kyubyong Park and Jongseok Kim, <https://github.com/Kyubyong/g2p> |
14
+ | Pronunciation dictionary (`assets/bundle/lexicon.txt`, 394,409 words), built by Phonlet AI from the LibriSpeech lexicon, the current CMU Pronouncing Dictionary and g2p_en predictions | LibriSpeech lexicon: public domain (OpenSLR SLR11); CMU Pronouncing Dictionary: Carnegie Mellon University's BSD-style licence (text below), Copyright (C) 1993-2015 Carnegie Mellon University | Vassil Panayotov, Daniel Povey and Sanjeev Khudanpur, <https://www.openslr.org/11/>; Carnegie Mellon University, <https://github.com/cmusphinx/cmudict> |
15
+ | Calibration data (`assets/bundle/`: `generator.json`, `policy.json`, `evidence/`): statistics of the `en-1` detector's scores, and the phone sequences of 72,656 held-out utterances (62.4 hours) converted from their transcripts; no audio | Derived from the corpora in the next table | As listed there |
16
+
17
+ The `en-1` model whose scores these statistics describe was trained on Common Voice, LibriSpeech
18
+ and GigaSpeech speech with MUSAN noise; its own notices ship with the model.
19
+
20
+ ### Corpora behind the calibration data
21
+
22
+ | Corpus | Part | Terms | Credit |
23
+ | --- | --- | --- | --- |
24
+ | AMI Meeting Corpus | single distant microphone (held-out statistics and phone sequences) | CC BY 4.0 | The AMI project; Jean Carletta et al., "The AMI Meeting Corpus: A Pre-Announcement", MLMI 2005, <https://groups.inf.ed.ac.uk/ami/corpus/> |
25
+ | Mozilla Common Voice 22.0, English | dev (held-out statistics and phone sequences), train (coverage statistics) | CC0 1.0 | The Common Voice contributors, <https://commonvoice.mozilla.org> |
26
+ | LibriSpeech ASR corpus | dev-clean, dev-other, test-clean, test-other (held-out statistics and phone sequences); train-clean-100, train-clean-360, train-other-500 (coverage statistics) | CC BY 4.0 | Vassil Panayotov, Guoguo Chen, Daniel Povey and Sanjeev Khudanpur, "LibriSpeech: an ASR corpus based on public domain audio books", ICASSP 2015, <https://www.openslr.org/12/> |
27
+ | GigaSpeech | L subset, train (coverage statistics) | SpeechColab terms of access: use only for non-commercial research and educational purposes; SpeechColab does not own the copyright of the audio | Guoguo Chen et al., "GigaSpeech: An Evolving, Multi-domain ASR Corpus with 10,000 Hours of Transcribed Audio", Interspeech 2021, <https://github.com/SpeechColab/GigaSpeech> |
28
+ | MUSAN | noise and music, mixed into the measured audio | CC BY 4.0; every recording is under a Creative Commons licence or in the US public domain, all allowing commercial use | David Snyder, Guoguo Chen and Daniel Povey, "MUSAN: A Music, Speech, and Noise Corpus", arXiv:1510.08484, 2015, <https://www.openslr.org/17/> |
29
+
30
+ Changes: the audio was resampled to 16 kHz, mixed with noise, scored by the `en-1` detector and
31
+ reduced to quantised score statistics; transcripts were converted to phone sequences. Licence
32
+ texts: CC BY 4.0 <https://creativecommons.org/licenses/by/4.0/legalcode>, CC0 1.0
33
+ <https://creativecommons.org/publicdomain/zero/1.0/legalcode>.
34
+
35
+ ## Algorithms reproduced from NumPy
36
+
37
+ `src/rng.rs` and `src/numeric.rs` reimplement NumPy's `SeedSequence`, its PCG64 generator
38
+ (Melissa O'Neill's PCG XSL-RR 128/64), `Generator.integers`, `random` and `choice`, pairwise
39
+ summation and `interp`, so that the output matches the reference bit for bit. NumPy is
40
+ Copyright (c) 2005-2026, NumPy Developers, BSD-3-Clause (text below).
41
+
42
+ ## Rust crates
43
+
44
+ Every crate compiled into the binaries or the WebAssembly module, from `Cargo.lock`
45
+ (`cargo tree -e normal`, crate version 0.2.0; the WebAssembly build has the same list without
46
+ `cpufeatures`). Where a crate offers a choice of licences, it is used here under the MIT licence;
47
+ the licence texts are below.
48
+
49
+ | Crate | Version | Licence | Copyright |
50
+ | --- | --- | --- | --- |
51
+ | [adler2](https://github.com/oyvindln/adler2) | 2.0.1 | 0BSD OR MIT OR Apache-2.0; used under MIT | Jonas Schievink, oyvindln (crate authors) |
52
+ | [anstream](https://github.com/rust-cli/anstyle) | 1.0.0 | MIT OR Apache-2.0; used under MIT | Copyright (c) Individual contributors |
53
+ | [anstyle](https://github.com/rust-cli/anstyle) | 1.0.14 | MIT OR Apache-2.0; used under MIT | Copyright (c) Individual contributors |
54
+ | [anstyle-parse](https://github.com/rust-cli/anstyle) | 1.0.0 | MIT OR Apache-2.0; used under MIT | Copyright (c) Individual contributors |
55
+ | [anstyle-query](https://github.com/rust-cli/anstyle) | 1.1.5 | MIT OR Apache-2.0; used under MIT | Copyright (c) Individual contributors |
56
+ | [block-buffer](https://github.com/RustCrypto/utils) | 0.10.4 | MIT OR Apache-2.0; used under MIT | Copyright (c) 2018-2019 The RustCrypto Project Developers |
57
+ | [cfg-if](https://github.com/rust-lang/cfg-if) | 1.0.5 | MIT OR Apache-2.0; used under MIT | Copyright (c) 2014 Alex Crichton |
58
+ | [clap](https://github.com/clap-rs/clap) | 4.6.7 | MIT OR Apache-2.0; used under MIT | Copyright (c) Individual contributors |
59
+ | [clap_builder](https://github.com/clap-rs/clap) | 4.6.7 | MIT OR Apache-2.0; used under MIT | Copyright (c) Individual contributors |
60
+ | [clap_lex](https://github.com/clap-rs/clap) | 1.1.1 | MIT OR Apache-2.0; used under MIT | Copyright (c) Individual contributors |
61
+ | [colorchoice](https://github.com/rust-cli/anstyle) | 1.0.5 | MIT OR Apache-2.0; used under MIT | Copyright (c) Individual contributors |
62
+ | [cpufeatures](https://github.com/RustCrypto/utils) | 0.2.17 | MIT OR Apache-2.0; used under MIT | Copyright (c) 2020-2025 The RustCrypto Project Developers |
63
+ | [crypto-common](https://github.com/RustCrypto/traits) | 0.1.7 | MIT OR Apache-2.0; used under MIT | Copyright (c) 2021 RustCrypto Developers |
64
+ | [digest](https://github.com/RustCrypto/traits) | 0.10.7 | MIT OR Apache-2.0; used under MIT | Copyright (c) 2017 Artyom Pavlov |
65
+ | [equivalent](https://github.com/indexmap-rs/equivalent) | 1.0.3 | Apache-2.0 OR MIT; used under MIT | Copyright (c) 2016--2023, the indexmap-rs contributors |
66
+ | [foldhash](https://github.com/orlp/foldhash) | 0.2.0 | Zlib | Copyright (c) 2024 Orson Peters |
67
+ | [generic-array](https://github.com/fizyk20/generic-array) | 0.14.7 | MIT | Copyright (c) 2015 Bartłomiej Kamiński |
68
+ | [hashbrown](https://github.com/rust-lang/hashbrown) | 0.17.1 | MIT OR Apache-2.0; used under MIT | Copyright (c) 2016 Amanieu d'Antras |
69
+ | [indexmap](https://github.com/indexmap-rs/indexmap) | 2.14.2 | Apache-2.0 OR MIT; used under MIT | Copyright (c) 2016--2017, the indexmap-rs contributors |
70
+ | [is_terminal_polyfill](https://github.com/polyfill-rs/is_terminal_polyfill) | 1.70.2 | MIT OR Apache-2.0; used under MIT | Copyright (c) Individual contributors |
71
+ | [itoa](https://github.com/dtolnay/itoa) | 1.0.18 | MIT OR Apache-2.0; used under MIT | David Tolnay (crate author) |
72
+ | [memchr](https://github.com/BurntSushi/memchr) | 2.8.3 | Unlicense OR MIT; used under MIT | Copyright (c) 2015 Andrew Gallant |
73
+ | [miniz_oxide](https://github.com/Frommi/miniz_oxide/tree/master/miniz_oxide) | 0.8.9 | MIT OR Zlib OR Apache-2.0; used under MIT | Copyright 2013-2014 RAD Game Tools and Valve Software; Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC; Copyright (c) 2017 Frommi; Copyright (c) 2017-2024 oyvindln |
74
+ | [serde](https://github.com/serde-rs/serde) | 1.0.229 | MIT OR Apache-2.0; used under MIT | Erick Tryzelaar, David Tolnay (crate authors) |
75
+ | [serde_core](https://github.com/serde-rs/serde) | 1.0.229 | MIT OR Apache-2.0; used under MIT | Erick Tryzelaar, David Tolnay (crate authors) |
76
+ | [serde_json](https://github.com/serde-rs/json) | 1.0.154 | MIT OR Apache-2.0; used under MIT | The serde-rs/json contributors |
77
+ | [sha2](https://github.com/RustCrypto/hashes) | 0.10.9 | MIT OR Apache-2.0; used under MIT | Copyright (c) 2006-2009 Graydon Hoare; Copyright (c) 2009-2013 Mozilla Foundation; Copyright (c) 2016 Artyom Pavlov |
78
+ | [strsim](https://github.com/rapidfuzz/strsim-rs) | 0.11.1 | MIT | Copyright (c) 2015 Danny Guo; Copyright (c) 2016 Titus Wormer; Copyright (c) 2018 Akash Kurdekar |
79
+ | [tinyvec](https://github.com/Lokathor/tinyvec) | 1.13.3 | Zlib OR Apache-2.0 OR MIT; used under MIT | Copyright (c) 2019 Daniel "Lokathor" Gee. |
80
+ | [typenum](https://github.com/paholg/typenum) | 1.20.1 | MIT OR Apache-2.0; used under MIT | Copyright (c) 2014 Paho Lurie-Gregg |
81
+ | [unicode-general-category](https://github.com/yeslogic/unicode-general-category) | 1.1.0 | Apache-2.0 | YesLogic Pty. Ltd. (crate author) |
82
+ | [unicode-normalization](https://github.com/unicode-rs/unicode-normalization) | 0.1.26 | (MIT OR Apache-2.0) AND Unicode-3.0; used under MIT AND Unicode-3.0 | Copyright (c) 2015 The Rust Project Developers; data tables Copyright © 1991-2023 Unicode, Inc. |
83
+ | [utf8parse](https://github.com/alacritty/vte) | 0.2.2 | Apache-2.0 OR MIT; used under MIT | Copyright (c) 2016 Joe Wilm |
84
+ | [zmij](https://github.com/dtolnay/zmij) | 1.0.23 | MIT | David Tolnay (crate author) |
85
+
86
+ Compile-time only, not in the binaries: the procedural-macro crates `clap_derive` 4.6.7, `serde_derive` 1.0.229, with `heck` 0.5.0 (MIT OR Apache-2.0), `proc-macro2` 1.0.107 (MIT OR Apache-2.0), `quote` 1.0.47 (MIT OR Apache-2.0), `syn` 3.0.9 (MIT OR Apache-2.0), `unicode-ident` 1.0.27 ((MIT OR Apache-2.0) AND Unicode-3.0); the macros themselves are MIT OR Apache-2.0. The
87
+ build-script dependencies (`miniz_oxide`, `serde_json`, `sha2`, `zip` and theirs) only verify and
88
+ pack the assets at build time.
89
+
90
+ ## Rust standard library and C runtime
91
+
92
+ | Part | Where | Licence | Copyright |
93
+ | --- | --- | --- | --- |
94
+ | Rust standard library, with the crates it is built from (in the WebAssembly module these include ports of Doug Lea's dlmalloc and of musl's math library) | All builds | MIT OR Apache-2.0, used under MIT | Copyrights retained by the Rust project's contributors, <https://github.com/rust-lang/rust> |
95
+ | musl C library, linked statically | Linux binary (`x86_64-unknown-linux-musl`) | MIT | Copyright © 2005-2020 Rich Felker, et al.; full statement below |
96
+ | LLVM libunwind, linked statically | Linux binary | Apache-2.0 WITH LLVM-exception | The LLVM Project; the exception lifts the notice conditions for compiled code, <https://llvm.org/LICENSE.txt> |
97
+
98
+ The Windows and macOS binaries use their platforms' system C runtime libraries.
99
+
100
+ ## Licence texts
101
+
102
+ ### Apache License 2.0
103
+
104
+ Applies to g2p_en and to `unicode-general-category`; also the alternative licence of most crates
105
+ above.
106
+
107
+ ```text
108
+ Apache License
109
+ Version 2.0, January 2004
110
+ http://www.apache.org/licenses/
111
+
112
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
113
+
114
+ 1. Definitions.
115
+
116
+ "License" shall mean the terms and conditions for use, reproduction,
117
+ and distribution as defined by Sections 1 through 9 of this document.
118
+
119
+ "Licensor" shall mean the copyright owner or entity authorized by
120
+ the copyright owner that is granting the License.
121
+
122
+ "Legal Entity" shall mean the union of the acting entity and all
123
+ other entities that control, are controlled by, or are under common
124
+ control with that entity. For the purposes of this definition,
125
+ "control" means (i) the power, direct or indirect, to cause the
126
+ direction or management of such entity, whether by contract or
127
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
128
+ outstanding shares, or (iii) beneficial ownership of such entity.
129
+
130
+ "You" (or "Your") shall mean an individual or Legal Entity
131
+ exercising permissions granted by this License.
132
+
133
+ "Source" form shall mean the preferred form for making modifications,
134
+ including but not limited to software source code, documentation
135
+ source, and configuration files.
136
+
137
+ "Object" form shall mean any form resulting from mechanical
138
+ transformation or translation of a Source form, including but
139
+ not limited to compiled object code, generated documentation,
140
+ and conversions to other media types.
141
+
142
+ "Work" shall mean the work of authorship, whether in Source or
143
+ Object form, made available under the License, as indicated by a
144
+ copyright notice that is included in or attached to the work
145
+ (an example is provided in the Appendix below).
146
+
147
+ "Derivative Works" shall mean any work, whether in Source or Object
148
+ form, that is based on (or derived from) the Work and for which the
149
+ editorial revisions, annotations, elaborations, or other modifications
150
+ represent, as a whole, an original work of authorship. For the purposes
151
+ of this License, Derivative Works shall not include works that remain
152
+ separable from, or merely link (or bind by name) to the interfaces of,
153
+ the Work and Derivative Works thereof.
154
+
155
+ "Contribution" shall mean any work of authorship, including
156
+ the original version of the Work and any modifications or additions
157
+ to that Work or Derivative Works thereof, that is intentionally
158
+ submitted to Licensor for inclusion in the Work by the copyright owner
159
+ or by an individual or Legal Entity authorized to submit on behalf of
160
+ the copyright owner. For the purposes of this definition, "submitted"
161
+ means any form of electronic, verbal, or written communication sent
162
+ to the Licensor or its representatives, including but not limited to
163
+ communication on electronic mailing lists, source code control systems,
164
+ and issue tracking systems that are managed by, or on behalf of, the
165
+ Licensor for the purpose of discussing and improving the Work, but
166
+ excluding communication that is conspicuously marked or otherwise
167
+ designated in writing by the copyright owner as "Not a Contribution."
168
+
169
+ "Contributor" shall mean Licensor and any individual or Legal Entity
170
+ on behalf of whom a Contribution has been received by Licensor and
171
+ subsequently incorporated within the Work.
172
+
173
+ 2. Grant of Copyright License. Subject to the terms and conditions of
174
+ this License, each Contributor hereby grants to You a perpetual,
175
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
176
+ copyright license to reproduce, prepare Derivative Works of,
177
+ publicly display, publicly perform, sublicense, and distribute the
178
+ Work and such Derivative Works in Source or Object form.
179
+
180
+ 3. Grant of Patent License. Subject to the terms and conditions of
181
+ this License, each Contributor hereby grants to You a perpetual,
182
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
183
+ (except as stated in this section) patent license to make, have made,
184
+ use, offer to sell, sell, import, and otherwise transfer the Work,
185
+ where such license applies only to those patent claims licensable
186
+ by such Contributor that are necessarily infringed by their
187
+ Contribution(s) alone or by combination of their Contribution(s)
188
+ with the Work to which such Contribution(s) was submitted. If You
189
+ institute patent litigation against any entity (including a
190
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
191
+ or a Contribution incorporated within the Work constitutes direct
192
+ or contributory patent infringement, then any patent licenses
193
+ granted to You under this License for that Work shall terminate
194
+ as of the date such litigation is filed.
195
+
196
+ 4. Redistribution. You may reproduce and distribute copies of the
197
+ Work or Derivative Works thereof in any medium, with or without
198
+ modifications, and in Source or Object form, provided that You
199
+ meet the following conditions:
200
+
201
+ (a) You must give any other recipients of the Work or
202
+ Derivative Works a copy of this License; and
203
+
204
+ (b) You must cause any modified files to carry prominent notices
205
+ stating that You changed the files; and
206
+
207
+ (c) You must retain, in the Source form of any Derivative Works
208
+ that You distribute, all copyright, patent, trademark, and
209
+ attribution notices from the Source form of the Work,
210
+ excluding those notices that do not pertain to any part of
211
+ the Derivative Works; and
212
+
213
+ (d) If the Work includes a "NOTICE" text file as part of its
214
+ distribution, then any Derivative Works that You distribute must
215
+ include a readable copy of the attribution notices contained
216
+ within such NOTICE file, excluding those notices that do not
217
+ pertain to any part of the Derivative Works, in at least one
218
+ of the following places: within a NOTICE text file distributed
219
+ as part of the Derivative Works; within the Source form or
220
+ documentation, if provided along with the Derivative Works; or,
221
+ within a display generated by the Derivative Works, if and
222
+ wherever such third-party notices normally appear. The contents
223
+ of the NOTICE file are for informational purposes only and
224
+ do not modify the License. You may add Your own attribution
225
+ notices within Derivative Works that You distribute, alongside
226
+ or as an addendum to the NOTICE text from the Work, provided
227
+ that such additional attribution notices cannot be construed
228
+ as modifying the License.
229
+
230
+ You may add Your own copyright statement to Your modifications and
231
+ may provide additional or different license terms and conditions
232
+ for use, reproduction, or distribution of Your modifications, or
233
+ for any such Derivative Works as a whole, provided Your use,
234
+ reproduction, and distribution of the Work otherwise complies with
235
+ the conditions stated in this License.
236
+
237
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
238
+ any Contribution intentionally submitted for inclusion in the Work
239
+ by You to the Licensor shall be under the terms and conditions of
240
+ this License, without any additional terms or conditions.
241
+ Notwithstanding the above, nothing herein shall supersede or modify
242
+ the terms of any separate license agreement you may have executed
243
+ with Licensor regarding such Contributions.
244
+
245
+ 6. Trademarks. This License does not grant permission to use the trade
246
+ names, trademarks, service marks, or product names of the Licensor,
247
+ except as required for reasonable and customary use in describing the
248
+ origin of the Work and reproducing the content of the NOTICE file.
249
+
250
+ 7. Disclaimer of Warranty. Unless required by applicable law or
251
+ agreed to in writing, Licensor provides the Work (and each
252
+ Contributor provides its Contributions) on an "AS IS" BASIS,
253
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
254
+ implied, including, without limitation, any warranties or conditions
255
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
256
+ PARTICULAR PURPOSE. You are solely responsible for determining the
257
+ appropriateness of using or redistributing the Work and assume any
258
+ risks associated with Your exercise of permissions under this License.
259
+
260
+ 8. Limitation of Liability. In no event and under no legal theory,
261
+ whether in tort (including negligence), contract, or otherwise,
262
+ unless required by applicable law (such as deliberate and grossly
263
+ negligent acts) or agreed to in writing, shall any Contributor be
264
+ liable to You for damages, including any direct, indirect, special,
265
+ incidental, or consequential damages of any character arising as a
266
+ result of this License or out of the use or inability to use the
267
+ Work (including but not limited to damages for loss of goodwill,
268
+ work stoppage, computer failure or malfunction, or any and all
269
+ other commercial damages or losses), even if such Contributor
270
+ has been advised of the possibility of such damages.
271
+
272
+ 9. Accepting Warranty or Additional Liability. While redistributing
273
+ the Work or Derivative Works thereof, You may choose to offer,
274
+ and charge a fee for, acceptance of support, warranty, indemnity,
275
+ or other liability obligations and/or rights consistent with this
276
+ License. However, in accepting such obligations, You may act only
277
+ on Your own behalf and on Your sole responsibility, not on behalf
278
+ of any other Contributor, and only if You agree to indemnify,
279
+ defend, and hold each Contributor harmless for any liability
280
+ incurred by, or claims asserted against, such Contributor by reason
281
+ of your accepting any such warranty or additional liability.
282
+
283
+ END OF TERMS AND CONDITIONS
284
+
285
+ APPENDIX: How to apply the Apache License to your work.
286
+
287
+ To apply the Apache License to your work, attach the following
288
+ boilerplate notice, with the fields enclosed by brackets "{}"
289
+ replaced with your own identifying information. (Don't include
290
+ the brackets!) The text should be enclosed in the appropriate
291
+ comment syntax for the file format. We also recommend that a
292
+ file or class name and description of purpose be included on the
293
+ same "printed page" as the copyright notice for easier
294
+ identification within third-party archives.
295
+
296
+ Copyright {yyyy} {name of copyright owner}
297
+
298
+ Licensed under the Apache License, Version 2.0 (the "License");
299
+ you may not use this file except in compliance with the License.
300
+ You may obtain a copy of the License at
301
+
302
+ http://www.apache.org/licenses/LICENSE-2.0
303
+
304
+ Unless required by applicable law or agreed to in writing, software
305
+ distributed under the License is distributed on an "AS IS" BASIS,
306
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
307
+ See the License for the specific language governing permissions and
308
+ limitations under the License.
309
+ ```
310
+
311
+ ### MIT License
312
+
313
+ Applies to the crates above with the copyright lines given in their rows, to the Rust standard
314
+ library, and to musl.
315
+
316
+ ```text
317
+ Permission is hereby granted, free of charge, to any person obtaining a copy
318
+ of this software and associated documentation files (the "Software"), to deal
319
+ in the Software without restriction, including without limitation the rights
320
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
321
+ copies of the Software, and to permit persons to whom the Software is
322
+ furnished to do so, subject to the following conditions:
323
+
324
+ The above copyright notice and this permission notice shall be included in all
325
+ copies or substantial portions of the Software.
326
+
327
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
328
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
329
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
330
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
331
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
332
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
333
+ SOFTWARE.
334
+ ```
335
+
336
+ ### zlib License (`foldhash`)
337
+
338
+ ```text
339
+ Copyright (c) 2024 Orson Peters
340
+
341
+ This software is provided 'as-is', without any express or implied warranty. In
342
+ no event will the authors be held liable for any damages arising from the use of
343
+ this software.
344
+
345
+ Permission is granted to anyone to use this software for any purpose, including
346
+ commercial applications, and to alter it and redistribute it freely, subject to
347
+ the following restrictions:
348
+
349
+ 1. The origin of this software must not be misrepresented; you must not claim
350
+ that you wrote the original software. If you use this software in a product,
351
+ an acknowledgment in the product documentation would be appreciated but is
352
+ not required.
353
+
354
+ 2. Altered source versions must be plainly marked as such, and must not be
355
+ misrepresented as being the original software.
356
+
357
+ 3. This notice may not be removed or altered from any source distribution.
358
+ ```
359
+
360
+ ### Unicode License v3 (Unicode data tables in `unicode-normalization`)
361
+
362
+ ```text
363
+ UNICODE LICENSE V3
364
+
365
+ COPYRIGHT AND PERMISSION NOTICE
366
+
367
+ Copyright © 1991-2023 Unicode, Inc.
368
+
369
+ NOTICE TO USER: Carefully read the following legal agreement. BY
370
+ DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
371
+ SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
372
+ TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
373
+ DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
374
+
375
+ Permission is hereby granted, free of charge, to any person obtaining a
376
+ copy of data files and any associated documentation (the "Data Files") or
377
+ software and any associated documentation (the "Software") to deal in the
378
+ Data Files or Software without restriction, including without limitation
379
+ the rights to use, copy, modify, merge, publish, distribute, and/or sell
380
+ copies of the Data Files or Software, and to permit persons to whom the
381
+ Data Files or Software are furnished to do so, provided that either (a)
382
+ this copyright and permission notice appear with all copies of the Data
383
+ Files or Software, or (b) this copyright and permission notice appear in
384
+ associated Documentation.
385
+
386
+ THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
387
+ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
388
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
389
+ THIRD PARTY RIGHTS.
390
+
391
+ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
392
+ BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
393
+ OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
394
+ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
395
+ ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
396
+ FILES OR SOFTWARE.
397
+
398
+ Except as contained in this notice, the name of a copyright holder shall
399
+ not be used in advertising or otherwise to promote the sale, use or other
400
+ dealings in these Data Files or Software without prior written
401
+ authorization of the copyright holder.
402
+ ```
403
+
404
+ ### CMU Pronouncing Dictionary
405
+
406
+ ```text
407
+ Copyright (C) 1993-2008 Carnegie Mellon University. All rights reserved.
408
+
409
+ Redistribution and use in source and binary forms, with or without
410
+ modification, are permitted provided that the following conditions
411
+ are met:
412
+
413
+ 1. Redistributions of source code must retain the above copyright
414
+ notice, this list of conditions and the following disclaimer.
415
+ The contents of this file are deemed to be source code.
416
+
417
+ 2. Redistributions in binary form must reproduce the above copyright
418
+ notice, this list of conditions and the following disclaimer in
419
+ the documentation and/or other materials provided with the
420
+ distribution.
421
+
422
+ This work was supported in part by funding from the Defense Advanced
423
+ Research Projects Agency, the Office of Naval Research and the National
424
+ Science Foundation of the United States of America, and by member
425
+ companies of the Carnegie Mellon Sphinx Speech Consortium. We acknowledge
426
+ the contributions of many volunteers to the expansion and improvement of
427
+ this dictionary.
428
+
429
+ THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND
430
+ ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
431
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
432
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY
433
+ NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
434
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
435
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
436
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
437
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
438
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
439
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
440
+ ```
441
+
442
+ ### NumPy (BSD-3-Clause)
443
+
444
+ ```text
445
+ Copyright (c) 2005-2026, NumPy Developers.
446
+ All rights reserved.
447
+
448
+ Redistribution and use in source and binary forms, with or without
449
+ modification, are permitted provided that the following conditions are
450
+ met:
451
+
452
+ * Redistributions of source code must retain the above copyright
453
+ notice, this list of conditions and the following disclaimer.
454
+
455
+ * Redistributions in binary form must reproduce the above
456
+ copyright notice, this list of conditions and the following
457
+ disclaimer in the documentation and/or other materials provided
458
+ with the distribution.
459
+
460
+ * Neither the name of the NumPy Developers nor the names of any
461
+ contributors may be used to endorse or promote products derived
462
+ from this software without specific prior written permission.
463
+
464
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
465
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
466
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
467
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
468
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
469
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
470
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
471
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
472
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
473
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
474
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
475
+ ```
476
+
477
+ ### musl
478
+
479
+ ```text
480
+ musl as a whole is licensed under the following standard MIT license:
481
+
482
+ ----------------------------------------------------------------------
483
+ Copyright © 2005-2020 Rich Felker, et al.
484
+
485
+ Permission is hereby granted, free of charge, to any person obtaining
486
+ a copy of this software and associated documentation files (the
487
+ "Software"), to deal in the Software without restriction, including
488
+ without limitation the rights to use, copy, modify, merge, publish,
489
+ distribute, sublicense, and/or sell copies of the Software, and to
490
+ permit persons to whom the Software is furnished to do so, subject to
491
+ the following conditions:
492
+
493
+ The above copyright notice and this permission notice shall be
494
+ included in all copies or substantial portions of the Software.
495
+
496
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
497
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
498
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
499
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
500
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
501
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
502
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
503
+ ----------------------------------------------------------------------
504
+
505
+ Authors/contributors include:
506
+
507
+ A. Wilcox
508
+ Ada Worcester
509
+ Alex Dowad
510
+ Alex Suykov
511
+ Alexander Monakov
512
+ Andre McCurdy
513
+ Andrew Kelley
514
+ Anthony G. Basile
515
+ Aric Belsito
516
+ Arvid Picciani
517
+ Bartosz Brachaczek
518
+ Benjamin Peterson
519
+ Bobby Bingham
520
+ Boris Brezillon
521
+ Brent Cook
522
+ Chris Spiegel
523
+ Clément Vasseur
524
+ Daniel Micay
525
+ Daniel Sabogal
526
+ Daurnimator
527
+ David Carlier
528
+ David Edelsohn
529
+ Denys Vlasenko
530
+ Dmitry Ivanov
531
+ Dmitry V. Levin
532
+ Drew DeVault
533
+ Emil Renner Berthing
534
+ Fangrui Song
535
+ Felix Fietkau
536
+ Felix Janda
537
+ Gianluca Anzolin
538
+ Hauke Mehrtens
539
+ He X
540
+ Hiltjo Posthuma
541
+ Isaac Dunham
542
+ Jaydeep Patil
543
+ Jens Gustedt
544
+ Jeremy Huntwork
545
+ Jo-Philipp Wich
546
+ Joakim Sindholt
547
+ John Spencer
548
+ Julien Ramseier
549
+ Justin Cormack
550
+ Kaarle Ritvanen
551
+ Khem Raj
552
+ Kylie McClain
553
+ Leah Neukirchen
554
+ Luca Barbato
555
+ Luka Perkov
556
+ Lynn Ochs
557
+ M Farkas-Dyck (Strake)
558
+ Mahesh Bodapati
559
+ Markus Wichmann
560
+ Masanori Ogino
561
+ Michael Clark
562
+ Michael Forney
563
+ Mikhail Kremnyov
564
+ Natanael Copa
565
+ Nicholas J. Kain
566
+ orc
567
+ Pascal Cuoq
568
+ Patrick Oppenlander
569
+ Petr Hosek
570
+ Petr Skocik
571
+ Pierre Carrier
572
+ Reini Urban
573
+ Rich Felker
574
+ Richard Pennington
575
+ Ryan Fairfax
576
+ Samuel Holland
577
+ Segev Finer
578
+ Shiz
579
+ sin
580
+ Solar Designer
581
+ Stefan Kristiansson
582
+ Stefan O'Rear
583
+ Szabolcs Nagy
584
+ Timo Teräs
585
+ Trutz Behn
586
+ Will Dietz
587
+ William Haddon
588
+ William Pitcock
589
+
590
+ Portions of this software are derived from third-party works licensed
591
+ under terms compatible with the above MIT license:
592
+
593
+ The TRE regular expression implementation (src/regex/reg* and
594
+ src/regex/tre*) is Copyright © 2001-2008 Ville Laurikari and licensed
595
+ under a 2-clause BSD license (license text in the source files). The
596
+ included version has been heavily modified by Rich Felker in 2012, in
597
+ the interests of size, simplicity, and namespace cleanliness.
598
+
599
+ Much of the math library code (src/math/* and src/complex/*) is
600
+ Copyright © 1993,2004 Sun Microsystems or
601
+ Copyright © 2003-2011 David Schultz or
602
+ Copyright © 2003-2009 Steven G. Kargl or
603
+ Copyright © 2003-2009 Bruce D. Evans or
604
+ Copyright © 2008 Stephen L. Moshier or
605
+ Copyright © 2017-2018 Arm Limited
606
+ and labelled as such in comments in the individual source files. All
607
+ have been licensed under extremely permissive terms.
608
+
609
+ The ARM memcpy code (src/string/arm/memcpy.S) is Copyright © 2008
610
+ The Android Open Source Project and is licensed under a two-clause BSD
611
+ license. It was taken from Bionic libc, used on Android.
612
+
613
+ The AArch64 memcpy and memset code (src/string/aarch64/*) are
614
+ Copyright © 1999-2019, Arm Limited.
615
+
616
+ The implementation of DES for crypt (src/crypt/crypt_des.c) is
617
+ Copyright © 1994 David Burren. It is licensed under a BSD license.
618
+
619
+ The implementation of blowfish crypt (src/crypt/crypt_blowfish.c) was
620
+ originally written by Solar Designer and placed into the public
621
+ domain. The code also comes with a fallback permissive license for use
622
+ in jurisdictions that may not recognize the public domain.
623
+
624
+ The smoothsort implementation (src/stdlib/qsort.c) is Copyright © 2011
625
+ Lynn Ochs and is licensed under an MIT-style license.
626
+
627
+ The x86_64 port was written by Nicholas J. Kain and is licensed under
628
+ the standard MIT terms.
629
+
630
+ The mips and microblaze ports were originally written by Richard
631
+ Pennington for use in the ellcc project. The original code was adapted
632
+ by Rich Felker for build system and code conventions during upstream
633
+ integration. It is licensed under the standard MIT terms.
634
+
635
+ The mips64 port was contributed by Imagination Technologies and is
636
+ licensed under the standard MIT terms.
637
+
638
+ The powerpc port was also originally written by Richard Pennington,
639
+ and later supplemented and integrated by John Spencer. It is licensed
640
+ under the standard MIT terms.
641
+
642
+ All other files which have no copyright comments are original works
643
+ produced specifically for use as part of this library, written either
644
+ by Rich Felker, the main author of the library, or by one or more
645
+ contibutors listed above. Details on authorship of individual files
646
+ can be found in the git version control history of the project. The
647
+ omission of copyright and license comments in each file is in the
648
+ interest of source tree size.
649
+
650
+ In addition, permission is hereby granted for all public header files
651
+ (include/* and arch/*/bits/*) and crt files intended to be linked into
652
+ applications (crt/*, ldso/dlstart.c, and arch/*/crt_arch.h) to omit
653
+ the copyright notice and permission notice otherwise required by the
654
+ license, and to use these files without any requirement of
655
+ attribution. These files include substantial contributions from:
656
+
657
+ Bobby Bingham
658
+ John Spencer
659
+ Nicholas J. Kain
660
+ Rich Felker
661
+ Richard Pennington
662
+ Stefan Kristiansson
663
+ Szabolcs Nagy
664
+
665
+ all of whom have explicitly granted such permission.
666
+
667
+ This file previously contained text expressing a belief that most of
668
+ the files covered by the above exception were sufficiently trivial not
669
+ to be subject to copyright, resulting in confusion over whether it
670
+ negated the permissions granted in the license. In the spirit of
671
+ permissive licensing, and of not having licensing issues being an
672
+ obstacle to adoption, that text has been removed.
673
+ ```
674
+
675
+ Parts of the musl math library, and of the Rust standard library's port of it, carry this notice:
676
+
677
+ ```text
678
+ Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
679
+
680
+ Developed at SunSoft, a Sun Microsystems, Inc. business.
681
+ Permission to use, copy, modify, and distribute this
682
+ software is freely granted, provided that this notice
683
+ is preserved.
684
+ ```
generator/wake_threshold.wasm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bbb5cb9e40b0941a53474dfc2206a1901c2fee8b935bd3763980f68bc1957107
3
+ size 18742088
generator/worker.js ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // The Phonlet Wake threshold generator in the browser: the same Rust code as the wake-threshold
2
+ // command-line tool, compiled to WebAssembly. One JSON request in, one keyword file out. Nothing
3
+ // leaves the page. While the module downloads, the worker posts {progress: [loaded, total]}.
4
+ let exports = null;
5
+ let loading = null;
6
+
7
+ async function download(url) {
8
+ const response = await fetch(url);
9
+ if (!response.ok) throw new Error(`cannot load the generator: HTTP ${response.status}`);
10
+ // Content-Length counts the bytes on the wire. A compressed response (GitHub Pages gzips the
11
+ // module) decodes to more than that, so it only estimates the progress; the chunks decide.
12
+ const length = Number(response.headers.get('content-length')) || 0;
13
+ if (!response.body || !length) return new Uint8Array(await response.arrayBuffer());
14
+ const chunks = [];
15
+ const reader = response.body.getReader();
16
+ let loaded = 0;
17
+ for (;;) {
18
+ const { done, value } = await reader.read();
19
+ if (done) break;
20
+ chunks.push(value);
21
+ loaded += value.length;
22
+ self.postMessage({ progress: [loaded, Math.max(length, loaded)] });
23
+ }
24
+ const bytes = new Uint8Array(loaded);
25
+ let offset = 0;
26
+ for (const chunk of chunks) {
27
+ bytes.set(chunk, offset);
28
+ offset += chunk.length;
29
+ }
30
+ return bytes;
31
+ }
32
+
33
+ async function load() {
34
+ const bytes = await download(new URL('./wake_threshold.wasm', self.location.href));
35
+ const { instance } = await WebAssembly.instantiate(bytes, {});
36
+ exports = instance.exports;
37
+ const result = call({ command: 'load' });
38
+ if (result.error) throw new Error(result.error);
39
+ }
40
+
41
+ function call(request) {
42
+ const bytes = new TextEncoder().encode(JSON.stringify(request));
43
+ const pointer = exports.wt_alloc(bytes.length);
44
+ new Uint8Array(exports.memory.buffer, pointer, bytes.length).set(bytes);
45
+ const length = exports.wt_call(pointer, bytes.length);
46
+ const out = new Uint8Array(exports.memory.buffer, exports.wt_result(), length);
47
+ return JSON.parse(new TextDecoder().decode(out));
48
+ }
49
+
50
+ self.onmessage = async ({ data }) => {
51
+ try {
52
+ loading ??= load();
53
+ await loading;
54
+ self.postMessage({ id: data.id, result: call(data.request) });
55
+ } catch (error) {
56
+ // A trap leaves the instance unusable: load a fresh one for the next request.
57
+ exports = null;
58
+ loading = null;
59
+ self.postMessage({ id: data.id, error: String(error?.message ?? error) });
60
+ }
61
+ };
icon.svg ADDED
index.html CHANGED
@@ -1,19 +1,114 @@
1
  <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  </html>
 
1
  <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>Phonlet Wake lab</title>
7
+ <meta
8
+ name="description"
9
+ content="Type any wake word, calibrate it in your browser and hear it detected live by the 1 MB Phonlet Wake model. Nothing is uploaded."
10
+ />
11
+ <link rel="icon" href="icon.svg" type="image/svg+xml" />
12
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
13
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
14
+ <link
15
+ rel="stylesheet"
16
+ href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600&family=Geist+Mono:wght@400;500&family=Instrument+Serif:ital@0;1&display=swap"
17
+ />
18
+ <link rel="stylesheet" href="style.css" />
19
+ <script type="module" src="app.mjs"></script>
20
+ </head>
21
+ <body>
22
+ <header class="top">
23
+ <a class="brand" href="https://phonletai.com" aria-label="Phonlet, home page">
24
+ <svg viewBox="0 0 64 64" aria-hidden="true">
25
+ <path d="M10 26h7v15h-7zM22 13h7v39h-7zM34 19h7v27h-7zM46 26h7v15h-7z" />
26
+ </svg>
27
+ <span class="word">phonlet<span class="dot">.</span></span>
28
+ </a>
29
+ <nav aria-label="Links">
30
+ <a href="https://phonletai.com/docs/">Docs</a>
31
+ <a href="https://huggingface.co/phonletai/wake-en-1">Model</a>
32
+ <a href="https://github.com/phonlet-ai/wake">GitHub</a>
33
+ </nav>
34
+ </header>
35
+
36
+ <main>
37
+ <section class="intro">
38
+ <p class="eyebrow">Phonlet Wake · en-1 · 1 MB · offline</p>
39
+ <h1>Any wake word. <em>Typed, not trained.</em></h1>
40
+ <p class="lede">
41
+ Type a phrase. The generator calibrates it here in your browser, then the engine listens
42
+ for it on your microphone. Nothing is uploaded.
43
+ </p>
44
+ </section>
45
+
46
+ <section class="lab" aria-label="Wake-word lab">
47
+ <div class="burst" id="burst" aria-hidden="true"></div>
48
+
49
+ <form id="add" class="add" autocomplete="off">
50
+ <label for="phrase">Add a phrase</label>
51
+ <div class="field">
52
+ <input
53
+ id="phrase"
54
+ name="phrase"
55
+ type="text"
56
+ maxlength="80"
57
+ placeholder="hey nova"
58
+ spellcheck="false"
59
+ />
60
+ <button type="submit" id="add-button">Add</button>
61
+ </div>
62
+ <p class="hint">
63
+ Two to four syllables work best. Names and made-up words get a predicted pronunciation;
64
+ write the sounds yourself as <code>zorblax=Z AO R B L AE K S</code>.
65
+ </p>
66
+ </form>
67
+
68
+ <ul id="phrases" class="phrases" aria-label="Phrases the engine listens for"></ul>
69
+
70
+ <div class="tune">
71
+ <label for="sensitivity">
72
+ Sensitivity <output id="sensitivity-value" for="sensitivity">0.50</output>
73
+ </label>
74
+ <input id="sensitivity" type="range" min="0" max="1" step="0.05" value="0.5" />
75
+ <p class="hint" id="rate">Aims at about 1 false alarm per hour of speech.</p>
76
+ </div>
77
+
78
+ <div class="actions">
79
+ <button type="button" id="listen" class="primary">Start listening</button>
80
+ <button type="button" id="download" class="ghost">Download keywords.json</button>
81
+ </div>
82
+
83
+ <div class="meter" aria-hidden="true"><span id="level"></span></div>
84
+ <p id="status" class="status" role="status" aria-live="polite">Loading the phrases…</p>
85
+
86
+ <section class="heard" aria-labelledby="heard-title">
87
+ <h2 id="heard-title">Heard <span id="heard-count">0</span></h2>
88
+ <ol id="heard"></ol>
89
+ </section>
90
+ </section>
91
+
92
+ <section class="facts" aria-label="Footprint">
93
+ <div><strong>1 MB</strong><span>one int8 model for every phrase</span></div>
94
+ <div><strong>1.05 MB</strong><span>of memory while listening</span></div>
95
+ <div><strong>0.7%</strong><span>of one laptop core, natively</span></div>
96
+ <div><strong>19%</strong><span>of one ESP32-S3 core</span></div>
97
+ </section>
98
+ </main>
99
+
100
+ <footer>
101
+ <p>
102
+ Runs the Phonlet Wake browser SDK, the <code>en-1</code> model and the threshold generator
103
+ of release v0.1.0, as WebAssembly in workers. SDKs for Python, Node.js, C / C++, Java,
104
+ Android, .NET and ESP32-S3: <a href="https://phonletai.com/docs/">phonletai.com/docs</a>.
105
+ </p>
106
+ <p>
107
+ Free for non-commercial use under the PolyForm Noncommercial License 1.0.0; commercial
108
+ licences: <a href="mailto:contact@phonletai.com">contact@phonletai.com</a>. Third-party
109
+ notices: <a href="wake/THIRD_PARTY_NOTICES.md">engine and model</a>,
110
+ <a href="generator/THIRD_PARTY_NOTICES.md">generator</a>.
111
+ </p>
112
+ </footer>
113
+ </body>
114
  </html>
style.css CHANGED
@@ -1,28 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  body {
2
- padding: 2rem;
3
- font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  }
5
 
 
 
 
 
 
 
 
 
 
 
6
  h1 {
7
- font-size: 16px;
8
- margin-top: 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  }
10
 
11
- p {
12
- color: rgb(107, 114, 128);
13
- font-size: 15px;
14
- margin-bottom: 10px;
15
- margin-top: 5px;
 
 
16
  }
17
 
18
- .card {
19
- max-width: 620px;
20
- margin: 0 auto;
21
- padding: 16px;
22
- border: 1px solid lightgray;
23
- border-radius: 16px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  }
25
 
26
- .card p:last-child {
27
- margin-bottom: 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  }
 
1
+ /* Phonlet Wake lab: the dark stage and orange accent of phonletai.com. */
2
+ :root {
3
+ color-scheme: dark;
4
+ --night: #0e0f0c;
5
+ --panel: #171814;
6
+ --panel-2: #1f201b;
7
+ --line: #2e2f28;
8
+ --ink: #f3efe6;
9
+ --muted: #a6a294;
10
+ --orange: #e95630;
11
+ --orange-deep: #c94322; /* white text on it passes WCAG AA */
12
+ --orange-text: #ff8a63;
13
+ --ok: #7fd1a0;
14
+ --sans: 'Geist', ui-sans-serif, system-ui, sans-serif;
15
+ --mono: 'Geist Mono', ui-monospace, monospace;
16
+ --serif: 'Instrument Serif', Georgia, serif;
17
+ }
18
+ * {
19
+ box-sizing: border-box;
20
+ }
21
+ html {
22
+ background: var(--night);
23
+ }
24
  body {
25
+ margin: 0;
26
+ min-height: 100vh;
27
+ color: var(--ink);
28
+ font: 16px/1.55 var(--sans);
29
+ background:
30
+ radial-gradient(60rem 30rem at 85% -10%, rgb(233 86 48 / 0.22), transparent 70%),
31
+ radial-gradient(40rem 24rem at -10% 30%, rgb(233 86 48 / 0.08), transparent 70%), var(--night);
32
+ }
33
+ a {
34
+ color: var(--orange-text);
35
+ }
36
+ a:hover {
37
+ color: var(--ink);
38
+ }
39
+ :focus-visible {
40
+ outline: 2px solid var(--orange-text);
41
+ outline-offset: 3px;
42
+ }
43
+ code {
44
+ font-family: var(--mono);
45
+ font-size: 0.9em;
46
+ color: var(--ink);
47
+ }
48
+
49
+ .top,
50
+ main,
51
+ footer {
52
+ width: min(920px, 100% - 32px);
53
+ margin-inline: auto;
54
+ }
55
+ .top {
56
+ display: flex;
57
+ align-items: center;
58
+ justify-content: space-between;
59
+ gap: 16px;
60
+ padding: 22px 0;
61
+ }
62
+ .brand {
63
+ display: inline-flex;
64
+ align-items: center;
65
+ gap: 8px;
66
+ color: var(--ink);
67
+ font-weight: 600;
68
+ font-size: 22px;
69
+ letter-spacing: -0.04em;
70
+ text-decoration: none;
71
+ }
72
+ .brand svg {
73
+ width: 24px;
74
+ height: 24px;
75
+ fill: var(--orange);
76
+ }
77
+ .brand .dot {
78
+ color: var(--orange);
79
+ }
80
+ .top nav {
81
+ display: flex;
82
+ gap: 18px;
83
+ font-size: 14px;
84
+ }
85
+ .top nav a {
86
+ color: var(--muted);
87
+ text-decoration: none;
88
+ }
89
+ .top nav a:hover {
90
+ color: var(--ink);
91
  }
92
 
93
+ .intro {
94
+ padding: clamp(24px, 6vw, 64px) 0 clamp(20px, 4vw, 40px);
95
+ }
96
+ .eyebrow {
97
+ margin: 0 0 14px;
98
+ color: var(--orange-text);
99
+ font: 500 12px/1 var(--mono);
100
+ letter-spacing: 0.14em;
101
+ text-transform: uppercase;
102
+ }
103
  h1 {
104
+ margin: 0;
105
+ font-size: clamp(40px, 8vw, 76px);
106
+ font-weight: 500;
107
+ line-height: 0.98;
108
+ letter-spacing: -0.05em;
109
+ }
110
+ h1 em {
111
+ font-family: var(--serif);
112
+ font-weight: 400;
113
+ color: var(--orange-text);
114
+ letter-spacing: -0.02em;
115
+ }
116
+ .lede {
117
+ max-width: 46ch;
118
+ margin: 20px 0 0;
119
+ color: var(--muted);
120
+ font-size: 18px;
121
+ }
122
+
123
+ .lab {
124
+ position: relative;
125
+ display: grid;
126
+ grid-template-columns: minmax(0, 1fr);
127
+ gap: 22px;
128
+ padding: clamp(20px, 4vw, 36px);
129
+ border: 1px solid var(--line);
130
+ border-radius: 22px;
131
+ background: linear-gradient(180deg, var(--panel), var(--night));
132
+ overflow: hidden;
133
+ }
134
+ label {
135
+ font-weight: 500;
136
+ }
137
+ .field {
138
+ display: flex;
139
+ gap: 10px;
140
+ margin-top: 8px;
141
+ }
142
+ input[type='text'] {
143
+ flex: 1;
144
+ min-width: 0;
145
+ padding: 13px 16px;
146
+ border: 1px solid var(--line);
147
+ border-radius: 12px;
148
+ background: var(--night);
149
+ color: var(--ink);
150
+ font: inherit;
151
+ font-size: 17px;
152
+ }
153
+ input[type='text']::placeholder {
154
+ color: #6f6c62;
155
+ }
156
+ button {
157
+ padding: 12px 20px;
158
+ border: 1px solid var(--line);
159
+ border-radius: 12px;
160
+ background: var(--panel-2);
161
+ color: var(--ink);
162
+ font: 500 15px var(--sans);
163
+ cursor: pointer;
164
+ }
165
+ button:hover:not(:disabled) {
166
+ border-color: var(--orange);
167
+ }
168
+ button:disabled {
169
+ opacity: 0.55;
170
+ cursor: progress;
171
+ }
172
+ button.primary {
173
+ border-color: var(--orange-deep);
174
+ background: var(--orange-deep);
175
+ color: #fff;
176
+ }
177
+ button.primary:hover:not(:disabled) {
178
+ background: #b33a1d;
179
+ }
180
+ button.primary.is-on {
181
+ background: transparent;
182
+ color: var(--orange-text);
183
+ }
184
+ button.ghost {
185
+ background: transparent;
186
+ }
187
+ .hint {
188
+ margin: 8px 0 0;
189
+ overflow-wrap: anywhere;
190
+ color: var(--muted);
191
+ font-size: 14px;
192
+ }
193
+
194
+ .phrases {
195
+ display: flex;
196
+ flex-wrap: wrap;
197
+ gap: 8px;
198
+ margin: 0;
199
+ padding: 0;
200
+ list-style: none;
201
+ }
202
+ .phrases li {
203
+ display: inline-flex;
204
+ align-items: center;
205
+ gap: 10px;
206
+ max-width: 100%;
207
+ padding: 7px 8px 7px 14px;
208
+ border: 1px solid var(--line);
209
+ border-radius: 999px;
210
+ background: var(--panel-2);
211
+ }
212
+ .phrases li.is-new {
213
+ border-color: var(--orange);
214
+ }
215
+ .phrases .name {
216
+ font-weight: 500;
217
+ overflow-wrap: anywhere;
218
+ }
219
+ .phrases .sounds {
220
+ color: var(--muted);
221
+ font: 12px var(--mono);
222
+ }
223
+ .phrases .tag {
224
+ padding: 2px 8px;
225
+ border-radius: 999px;
226
+ background: rgb(233 86 48 / 0.14);
227
+ color: var(--orange-text);
228
+ font: 500 11px var(--mono);
229
+ letter-spacing: 0.06em;
230
+ text-transform: uppercase;
231
+ }
232
+ .phrases .tag.warn {
233
+ background: rgb(255 196 0 / 0.14);
234
+ color: #ffd166;
235
+ }
236
+ .phrases button {
237
+ width: 28px;
238
+ height: 28px;
239
+ padding: 0;
240
+ border-radius: 50%;
241
+ line-height: 1;
242
+ }
243
+
244
+ .tune label {
245
+ display: flex;
246
+ justify-content: space-between;
247
+ }
248
+ .tune output {
249
+ font-family: var(--mono);
250
+ color: var(--orange-text);
251
+ }
252
+ input[type='range'] {
253
+ width: 100%;
254
+ margin-top: 10px;
255
+ accent-color: var(--orange);
256
  }
257
 
258
+ .actions {
259
+ display: flex;
260
+ flex-wrap: wrap;
261
+ gap: 10px;
262
+ }
263
+ .actions .primary {
264
+ min-width: 180px;
265
  }
266
 
267
+ .meter {
268
+ height: 6px;
269
+ border-radius: 999px;
270
+ background: var(--panel-2);
271
+ overflow: hidden;
272
+ }
273
+ .meter span {
274
+ display: block;
275
+ height: 100%;
276
+ width: 0;
277
+ border-radius: inherit;
278
+ background: linear-gradient(90deg, var(--orange), #ffb08a);
279
+ transition: width 80ms linear;
280
+ }
281
+ .status {
282
+ min-height: 1.55em;
283
+ margin: -8px 0 0;
284
+ color: var(--muted);
285
+ }
286
+ .status.is-error {
287
+ color: #ff9b8a;
288
  }
289
 
290
+ .heard h2 {
291
+ margin: 0 0 8px;
292
+ font: 500 12px var(--mono);
293
+ letter-spacing: 0.14em;
294
+ text-transform: uppercase;
295
+ color: var(--muted);
296
+ }
297
+ .heard h2 span {
298
+ color: var(--orange-text);
299
+ }
300
+ .heard ol {
301
+ display: grid;
302
+ gap: 6px;
303
+ margin: 0;
304
+ padding: 0;
305
+ list-style: none;
306
+ }
307
+ .heard li {
308
+ display: flex;
309
+ justify-content: space-between;
310
+ gap: 12px;
311
+ padding: 10px 14px;
312
+ border-radius: 12px;
313
+ background: var(--panel-2);
314
+ }
315
+ .heard li time {
316
+ color: var(--muted);
317
+ font: 13px var(--mono);
318
+ }
319
+ .heard li:first-child {
320
+ outline: 1px solid rgb(233 86 48 / 0.5);
321
+ }
322
+
323
+ .burst {
324
+ position: absolute;
325
+ inset: 0;
326
+ display: grid;
327
+ place-items: center;
328
+ pointer-events: none;
329
+ opacity: 0;
330
+ font: italic 400 clamp(40px, 9vw, 88px) / 1 var(--serif);
331
+ color: #fff;
332
+ text-align: center;
333
+ background: radial-gradient(circle at center, rgb(233 86 48 / 0.55), transparent 65%);
334
+ }
335
+ .burst.is-on {
336
+ animation: burst 1.4s ease-out;
337
+ }
338
+ @keyframes burst {
339
+ 0% {
340
+ opacity: 0;
341
+ transform: scale(0.92);
342
+ }
343
+ 15% {
344
+ opacity: 1;
345
+ transform: scale(1);
346
+ }
347
+ 100% {
348
+ opacity: 0;
349
+ transform: scale(1.04);
350
+ }
351
+ }
352
+
353
+ .facts {
354
+ display: grid;
355
+ grid-template-columns: repeat(4, minmax(0, 1fr));
356
+ gap: 12px;
357
+ margin: 28px 0;
358
+ }
359
+ .facts div {
360
+ padding: 18px;
361
+ border: 1px solid var(--line);
362
+ border-radius: 16px;
363
+ }
364
+ .facts strong {
365
+ display: block;
366
+ font-size: 28px;
367
+ font-weight: 500;
368
+ letter-spacing: -0.04em;
369
+ }
370
+ .facts span {
371
+ color: var(--muted);
372
+ font-size: 14px;
373
+ }
374
+
375
+ footer {
376
+ padding: 8px 0 40px;
377
+ color: var(--muted);
378
+ font-size: 14px;
379
+ }
380
+
381
+ @media (max-width: 720px) {
382
+ .facts {
383
+ grid-template-columns: repeat(2, minmax(0, 1fr));
384
+ }
385
+ .phrases .sounds {
386
+ display: none;
387
+ }
388
+ .top nav {
389
+ gap: 12px;
390
+ }
391
+ }
392
+ @media (prefers-reduced-motion: reduce) {
393
+ .burst.is-on {
394
+ animation: burst-still 1.4s steps(1, end);
395
+ }
396
+ @keyframes burst-still {
397
+ 0% {
398
+ opacity: 1;
399
+ }
400
+ 100% {
401
+ opacity: 0;
402
+ }
403
+ }
404
+ .meter span {
405
+ transition: none;
406
+ }
407
  }
wake/LICENSE ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Required Notice: Copyright 2026 Phonlet AI (https://phonletai.com)
2
+
3
+ # PolyForm Noncommercial License 1.0.0
4
+
5
+ <https://polyformproject.org/licenses/noncommercial/1.0.0>
6
+
7
+ ## Acceptance
8
+
9
+ In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
10
+
11
+ ## Copyright License
12
+
13
+ The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
14
+
15
+ ## Distribution License
16
+
17
+ The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
18
+
19
+ ## Notices
20
+
21
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
22
+
23
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
24
+
25
+ ## Changes and New Works License
26
+
27
+ The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
28
+
29
+ ## Patent License
30
+
31
+ The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
32
+
33
+ ## Noncommercial Purposes
34
+
35
+ Any noncommercial purpose is a permitted purpose.
36
+
37
+ ## Personal Uses
38
+
39
+ Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose.
40
+
41
+ ## Noncommercial Organizations
42
+
43
+ Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding.
44
+
45
+ ## Fair Use
46
+
47
+ You may have "fair use" rights for the software under the law. These terms do not limit them.
48
+
49
+ ## No Other Rights
50
+
51
+ These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
52
+
53
+ ## Patent Defense
54
+
55
+ If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
56
+
57
+ ## Violations
58
+
59
+ The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
60
+
61
+ ## No Liability
62
+
63
+ ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
64
+
65
+ ## Definitions
66
+
67
+ The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
68
+
69
+ **You** refers to the individual or entity agreeing to these terms.
70
+
71
+ **Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
72
+
73
+ **Your licenses** are all the licenses granted to you for the software under these terms.
74
+
75
+ **Use** means anything you do with the software requiring one of your licenses.
wake/README.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Phonlet Wake for browsers
2
+
3
+ `phonlet-ai-wake-web-0.1.0.tgz` in the [release](https://github.com/phonlet-ai/wake/releases/tag/v0.1.0) contains the worker, scalar/SIMD WASM runtimes, TypeScript declarations and optional capture helper. The English model is a separate package. Copy package assets to your server, preserving their relative layout.
4
+
5
+ ```js
6
+ import {Wake} from './vendor/wake/index.mjs';
7
+ const wake = await Wake.create({model:'./assets/model.pwake', keywords:'./assets/keywords.json', sensitivity:0.5});
8
+ try {
9
+ console.log(await wake.process(new Int16Array(512)));
10
+ console.log(await wake.finish());
11
+ } finally { await wake.close(); }
12
+ ```
13
+
14
+ Use localhost or HTTPS, serve `.mjs` as JavaScript and `.wasm` as `application/wasm`, and allow same-origin workers in CSP (`worker-src 'self'`; WASM execution may require `'wasm-unsafe-eval'`). No CDN, activation service, lexicon or enrollment endpoint is contacted. The default backend is scalar; `simd:true` explicitly requests the SIMD build. Await initialization before submitting mono, 16 kHz PCM16.
15
+
16
+ Worker processing is serialized and each promise resolves after processing. The limit is **4096 unacknowledged samples, including the in-flight call**; split large files into chunks and await each. Input is copied before transferring to the worker. Overload rejects explicitly. `finish()` drains accepted work and discards the partial frame; `close()` releases/terminates the worker. Both are idempotent.
17
+
18
+ The `./capture` export provides `WakeManager({wake, onDetection, onError, audioContext?, stream?})`. Call `start()`, `stop()`, `close()` and await each. Capture requires an actual 16 kHz AudioContext. Browser downmixing uses one channel; float samples are clamped/rounded to PCM16. Requested echo cancellation, noise suppression and automatic gain control are disabled. There is no SDK resampler. The helper stops owned tracks and closes owned contexts; borrowed resources stay open. Callbacks must be synchronous, and callback failures stop capture through `onError`. Restart creates fresh stream state. Physical microphones and other browsers still need device qualification.
19
+
20
+ `model` is a URL or bytes. `keywords` is a keyword file as the threshold generator writes it: its URL, the parsed object, or just the array of phrases written in code, each with its pronunciations and calibrated thresholds (a per-phrase `sensitivity` is optional). URLs resolve against the page. A keyword file that names its model (`model.sha256`) is refused for any other model. See [phrases and keyword files](../../docs/keywords.md).
wake/THIRD_PARTY_NOTICES.md ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Third-party notices
2
+
3
+ Phonlet Wake (the engine, the `en-1` model, the English phrases and the SDKs) is Copyright 2026
4
+ Phonlet AI and licensed under the PolyForm Noncommercial License 1.0.0, in the file `LICENSE`.
5
+ Commercial licences: `COMMERCIAL.md`, or contact@phonletai.com. This file names the work of others
6
+ that is built into what this repository ships, or that the `en-1` model and the English phrases
7
+ were made from, with the terms and the credit each one asks for.
8
+
9
+ ## Code
10
+
11
+ The engine (`engine/`, `include/`), the ESP32-S3 acoustic engine and every SDK are Phonlet AI's own
12
+ code. No third-party source is copied into them; the JSON reader, the FFT and the WAV reader are
13
+ written for this product. Third-party code enters only as the runtime libraries of the compilers
14
+ that build them.
15
+
16
+ ### WebAssembly engine (`sdk/web/dist/`)
17
+
18
+ The `.wasm` files and their `.mjs` loaders are built with Emscripten and contain parts of its
19
+ runtime:
20
+
21
+ | Component | Licence | Copyright |
22
+ | --- | --- | --- |
23
+ | Emscripten runtime and the generated loader | MIT (also offered under the University of Illinois/NCSA Open Source License) | Copyright (c) 2010-2014 Emscripten authors |
24
+ | Path helpers in the loader, taken by Emscripten from Node.js | MIT | Copyright Joyent, Inc. and other Node contributors |
25
+ | musl C library, as bundled with Emscripten | MIT | Copyright © 2005-2020 Rich Felker, et al.; full statement below |
26
+ | dlmalloc memory allocator | CC0 1.0 (public domain) | Written by Doug Lea |
27
+ | LLVM libc++, libc++abi, libunwind and compiler-rt | Apache-2.0 WITH LLVM-exception | The LLVM Project; the exception lifts the notice conditions for compiled code, <https://llvm.org/LICENSE.txt> |
28
+
29
+ ### Native libraries
30
+
31
+ Native builds link the C and C++ runtime of the toolchain that builds them: GCC's libstdc++ and
32
+ libgcc (GPL-3.0 with the GCC Runtime Library Exception), LLVM libc++ in the Android NDK
33
+ (Apache-2.0 WITH LLVM-exception), the platform runtimes on Apple systems, and the ESP-IDF
34
+ runtime inside an ESP32 application's own build. None of them is part of this repository, and
35
+ their exceptions let compiled programs ship without their notices.
36
+
37
+ The prebuilt Windows x64 library (`kws_engine.dll`) is built with Microsoft Visual C++ and links
38
+ its C and C++ runtime statically (`/MT`), as the Visual Studio license terms allow for
39
+ redistributable code; it needs no separate runtime installation.
40
+
41
+ Dependencies that an SDK declares (NumPy for Python; React, React Native and Flutter as peers) are
42
+ installed by their package managers under their own licences and are not part of these packages.
43
+
44
+ ## The `en-1` model
45
+
46
+ `resources/models/en-1/model.pwake` holds weights that Phonlet AI trained from random
47
+ initialisation, with no pretrained or teacher model, and input normalisation statistics computed
48
+ from the training audio. It contains no audio, transcripts or features from the material below.
49
+ Changes made to that material: audio resampled to 16 kHz, mixed with noise and simulated rooms, and
50
+ used to train the model; transcripts converted to phone sequences.
51
+
52
+ ### Speech, 4,851 indexed hours
53
+
54
+ | Corpus | Part | Hours | Terms | Credit |
55
+ | --- | --- | ---: | --- | --- |
56
+ | Mozilla Common Voice 22.0, English | train | 1,521.2 | CC0 1.0 | The Common Voice contributors, <https://commonvoice.mozilla.org> |
57
+ | LibriSpeech ASR corpus | train-clean-100, train-clean-360, train-other-500 | 961.1 | CC BY 4.0 | Vassil Panayotov, Guoguo Chen, Daniel Povey and Sanjeev Khudanpur, "LibriSpeech: an ASR corpus based on public domain audio books", ICASSP 2015, <https://www.openslr.org/12/>; read by LibriVox volunteers |
58
+ | GigaSpeech | L subset, train | 2,368.8 | SpeechColab terms of access: use only for non-commercial research and educational purposes; SpeechColab does not own the copyright of the audio (audiobooks, podcasts and online video) | Guoguo Chen et al., "GigaSpeech: An Evolving, Multi-domain ASR Corpus with 10,000 Hours of Transcribed Audio", Interspeech 2021, <https://github.com/SpeechColab/GigaSpeech> |
59
+
60
+ ### Noise and rooms
61
+
62
+ | Material | Terms | Credit |
63
+ | --- | --- | --- |
64
+ | MUSAN music, speech and noise (1,999 recordings, 109.3 hours) | CC BY 4.0; every recording is under a Creative Commons licence or in the US public domain, all allowing commercial use; per-recording licences and credits are in the corpus's `LICENSE` files | David Snyder, Guoguo Chen and Daniel Povey, "MUSAN: A Music, Speech, and Noise Corpus", arXiv:1510.08484, 2015, <https://www.openslr.org/17/> |
65
+ | Room impulse responses (100,000 rooms) | Simulated by Phonlet AI; no recorded responses | None |
66
+
67
+ ### Pronunciations
68
+
69
+ Training transcripts were mapped to phones with a 394,409-word dictionary:
70
+
71
+ | Source | Words | Terms | Credit |
72
+ | --- | ---: | --- | --- |
73
+ | LibriSpeech lexicon (`librispeech-lexicon.txt`) | 199,534 | Public domain (OpenSLR SLR11) | Vassil Panayotov, Daniel Povey and Sanjeev Khudanpur, <https://www.openslr.org/11/> |
74
+ | CMU Pronouncing Dictionary | 58,060 | Carnegie Mellon University's BSD-style licence, text below | Carnegie Mellon University, <https://github.com/cmusphinx/cmudict> |
75
+ | g2p_en 2.1.0, for words neither source has | 136,815 | The tool is Apache-2.0; the entries are its generated output | Kyubyong Park and Jongseok Kim, <https://github.com/Kyubyong/g2p> |
76
+
77
+ ## The English phrases
78
+
79
+ `resources/keywords/en.json` takes its pronunciations from the same dictionary. Its thresholds come
80
+ from Phonlet AI's enrollment tool, which measured the `en-1` detector on the material below; none
81
+ of it is included.
82
+
83
+ | Corpus | Part | Terms | Credit |
84
+ | --- | --- | --- | --- |
85
+ | AMI Meeting Corpus | single distant microphone | CC BY 4.0 | The AMI project; Jean Carletta et al., "The AMI Meeting Corpus: A Pre-Announcement", MLMI 2005, <https://groups.inf.ed.ac.uk/ami/corpus/> |
86
+ | Mozilla Common Voice 22.0, English | dev, and train for phone coverage | CC0 1.0 | As above |
87
+ | LibriSpeech ASR corpus | dev-clean, dev-other, test-clean, test-other, and train for phone coverage | CC BY 4.0 | As above |
88
+ | GigaSpeech | L subset, train, for phone coverage | SpeechColab terms of access, as above | As above |
89
+ | MUSAN | music and noise | CC BY 4.0 | As above |
90
+
91
+ Licence texts: CC BY 4.0 <https://creativecommons.org/licenses/by/4.0/legalcode>, CC0 1.0
92
+ <https://creativecommons.org/publicdomain/zero/1.0/legalcode>.
93
+
94
+ ## Notices
95
+
96
+ ### Emscripten
97
+
98
+ The AUTHORS file: <https://github.com/emscripten-core/emscripten/blob/main/AUTHORS>.
99
+
100
+ ```text
101
+ Copyright (c) 2010-2014 Emscripten authors, see AUTHORS file.
102
+
103
+ Permission is hereby granted, free of charge, to any person obtaining a copy
104
+ of this software and associated documentation files (the "Software"), to deal
105
+ in the Software without restriction, including without limitation the rights
106
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
107
+ copies of the Software, and to permit persons to whom the Software is
108
+ furnished to do so, subject to the following conditions:
109
+
110
+ The above copyright notice and this permission notice shall be included in
111
+ all copies or substantial portions of the Software.
112
+
113
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
114
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
115
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
116
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
117
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
118
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
119
+ THE SOFTWARE.
120
+ ```
121
+
122
+ ### Node.js (path helpers in the Emscripten loader)
123
+
124
+ ```text
125
+ Copyright Joyent, Inc. and other Node contributors. All rights reserved.
126
+ Permission is hereby granted, free of charge, to any person obtaining a copy
127
+ of this software and associated documentation files (the "Software"), to
128
+ deal in the Software without restriction, including without limitation the
129
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
130
+ sell copies of the Software, and to permit persons to whom the Software is
131
+ furnished to do so, subject to the following conditions:
132
+
133
+ The above copyright notice and this permission notice shall be included in
134
+ all copies or substantial portions of the Software.
135
+
136
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
137
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
138
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
139
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
140
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
141
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
142
+ IN THE SOFTWARE.
143
+ ```
144
+
145
+ ### musl
146
+
147
+ ```text
148
+ musl as a whole is licensed under the following standard MIT license:
149
+
150
+ ----------------------------------------------------------------------
151
+ Copyright © 2005-2020 Rich Felker, et al.
152
+
153
+ Permission is hereby granted, free of charge, to any person obtaining
154
+ a copy of this software and associated documentation files (the
155
+ "Software"), to deal in the Software without restriction, including
156
+ without limitation the rights to use, copy, modify, merge, publish,
157
+ distribute, sublicense, and/or sell copies of the Software, and to
158
+ permit persons to whom the Software is furnished to do so, subject to
159
+ the following conditions:
160
+
161
+ The above copyright notice and this permission notice shall be
162
+ included in all copies or substantial portions of the Software.
163
+
164
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
165
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
166
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
167
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
168
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
169
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
170
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
171
+ ----------------------------------------------------------------------
172
+
173
+ Authors/contributors include:
174
+
175
+ A. Wilcox
176
+ Ada Worcester
177
+ Alex Dowad
178
+ Alex Suykov
179
+ Alexander Monakov
180
+ Andre McCurdy
181
+ Andrew Kelley
182
+ Anthony G. Basile
183
+ Aric Belsito
184
+ Arvid Picciani
185
+ Bartosz Brachaczek
186
+ Benjamin Peterson
187
+ Bobby Bingham
188
+ Boris Brezillon
189
+ Brent Cook
190
+ Chris Spiegel
191
+ Clément Vasseur
192
+ Daniel Micay
193
+ Daniel Sabogal
194
+ Daurnimator
195
+ David Carlier
196
+ David Edelsohn
197
+ Denys Vlasenko
198
+ Dmitry Ivanov
199
+ Dmitry V. Levin
200
+ Drew DeVault
201
+ Emil Renner Berthing
202
+ Fangrui Song
203
+ Felix Fietkau
204
+ Felix Janda
205
+ Gianluca Anzolin
206
+ Hauke Mehrtens
207
+ He X
208
+ Hiltjo Posthuma
209
+ Isaac Dunham
210
+ Jaydeep Patil
211
+ Jens Gustedt
212
+ Jeremy Huntwork
213
+ Jo-Philipp Wich
214
+ Joakim Sindholt
215
+ John Spencer
216
+ Julien Ramseier
217
+ Justin Cormack
218
+ Kaarle Ritvanen
219
+ Khem Raj
220
+ Kylie McClain
221
+ Leah Neukirchen
222
+ Luca Barbato
223
+ Luka Perkov
224
+ Lynn Ochs
225
+ M Farkas-Dyck (Strake)
226
+ Mahesh Bodapati
227
+ Markus Wichmann
228
+ Masanori Ogino
229
+ Michael Clark
230
+ Michael Forney
231
+ Mikhail Kremnyov
232
+ Natanael Copa
233
+ Nicholas J. Kain
234
+ orc
235
+ Pascal Cuoq
236
+ Patrick Oppenlander
237
+ Petr Hosek
238
+ Petr Skocik
239
+ Pierre Carrier
240
+ Reini Urban
241
+ Rich Felker
242
+ Richard Pennington
243
+ Ryan Fairfax
244
+ Samuel Holland
245
+ Segev Finer
246
+ Shiz
247
+ sin
248
+ Solar Designer
249
+ Stefan Kristiansson
250
+ Stefan O'Rear
251
+ Szabolcs Nagy
252
+ Timo Teräs
253
+ Trutz Behn
254
+ Will Dietz
255
+ William Haddon
256
+ William Pitcock
257
+
258
+ Portions of this software are derived from third-party works licensed
259
+ under terms compatible with the above MIT license:
260
+
261
+ The TRE regular expression implementation (src/regex/reg* and
262
+ src/regex/tre*) is Copyright © 2001-2008 Ville Laurikari and licensed
263
+ under a 2-clause BSD license (license text in the source files). The
264
+ included version has been heavily modified by Rich Felker in 2012, in
265
+ the interests of size, simplicity, and namespace cleanliness.
266
+
267
+ Much of the math library code (src/math/* and src/complex/*) is
268
+ Copyright © 1993,2004 Sun Microsystems or
269
+ Copyright © 2003-2011 David Schultz or
270
+ Copyright © 2003-2009 Steven G. Kargl or
271
+ Copyright © 2003-2009 Bruce D. Evans or
272
+ Copyright © 2008 Stephen L. Moshier or
273
+ Copyright © 2017-2018 Arm Limited
274
+ and labelled as such in comments in the individual source files. All
275
+ have been licensed under extremely permissive terms.
276
+
277
+ The ARM memcpy code (src/string/arm/memcpy.S) is Copyright © 2008
278
+ The Android Open Source Project and is licensed under a two-clause BSD
279
+ license. It was taken from Bionic libc, used on Android.
280
+
281
+ The AArch64 memcpy and memset code (src/string/aarch64/*) are
282
+ Copyright © 1999-2019, Arm Limited.
283
+
284
+ The implementation of DES for crypt (src/crypt/crypt_des.c) is
285
+ Copyright © 1994 David Burren. It is licensed under a BSD license.
286
+
287
+ The implementation of blowfish crypt (src/crypt/crypt_blowfish.c) was
288
+ originally written by Solar Designer and placed into the public
289
+ domain. The code also comes with a fallback permissive license for use
290
+ in jurisdictions that may not recognize the public domain.
291
+
292
+ The smoothsort implementation (src/stdlib/qsort.c) is Copyright © 2011
293
+ Lynn Ochs and is licensed under an MIT-style license.
294
+
295
+ The x86_64 port was written by Nicholas J. Kain and is licensed under
296
+ the standard MIT terms.
297
+
298
+ The mips and microblaze ports were originally written by Richard
299
+ Pennington for use in the ellcc project. The original code was adapted
300
+ by Rich Felker for build system and code conventions during upstream
301
+ integration. It is licensed under the standard MIT terms.
302
+
303
+ The mips64 port was contributed by Imagination Technologies and is
304
+ licensed under the standard MIT terms.
305
+
306
+ The powerpc port was also originally written by Richard Pennington,
307
+ and later supplemented and integrated by John Spencer. It is licensed
308
+ under the standard MIT terms.
309
+
310
+ All other files which have no copyright comments are original works
311
+ produced specifically for use as part of this library, written either
312
+ by Rich Felker, the main author of the library, or by one or more
313
+ contibutors listed above. Details on authorship of individual files
314
+ can be found in the git version control history of the project. The
315
+ omission of copyright and license comments in each file is in the
316
+ interest of source tree size.
317
+
318
+ In addition, permission is hereby granted for all public header files
319
+ (include/* and arch/*/bits/*) and crt files intended to be linked into
320
+ applications (crt/*, ldso/dlstart.c, and arch/*/crt_arch.h) to omit
321
+ the copyright notice and permission notice otherwise required by the
322
+ license, and to use these files without any requirement of
323
+ attribution. These files include substantial contributions from:
324
+
325
+ Bobby Bingham
326
+ John Spencer
327
+ Nicholas J. Kain
328
+ Rich Felker
329
+ Richard Pennington
330
+ Stefan Kristiansson
331
+ Szabolcs Nagy
332
+
333
+ all of whom have explicitly granted such permission.
334
+
335
+ This file previously contained text expressing a belief that most of
336
+ the files covered by the above exception were sufficiently trivial not
337
+ to be subject to copyright, resulting in confusion over whether it
338
+ negated the permissions granted in the license. In the spirit of
339
+ permissive licensing, and of not having licensing issues being an
340
+ obstacle to adoption, that text has been removed.
341
+ ```
342
+
343
+ Parts of the musl math library carry this notice:
344
+
345
+ ```text
346
+ Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
347
+
348
+ Developed at SunSoft, a Sun Microsystems, Inc. business.
349
+ Permission to use, copy, modify, and distribute this
350
+ software is freely granted, provided that this notice
351
+ is preserved.
352
+ ```
353
+
354
+ ### CMU Pronouncing Dictionary
355
+
356
+ ```text
357
+ Copyright (C) 1993-2015 Carnegie Mellon University. All rights reserved.
358
+
359
+ Redistribution and use in source and binary forms, with or without
360
+ modification, are permitted provided that the following conditions
361
+ are met:
362
+
363
+ 1. Redistributions of source code must retain the above copyright
364
+ notice, this list of conditions and the following disclaimer.
365
+ The contents of this file are deemed to be source code.
366
+
367
+ 2. Redistributions in binary form must reproduce the above copyright
368
+ notice, this list of conditions and the following disclaimer in
369
+ the documentation and/or other materials provided with the
370
+ distribution.
371
+
372
+ This work was supported in part by funding from the Defense Advanced
373
+ Research Projects Agency, the Office of Naval Research and the National
374
+ Science Foundation of the United States of America, and by member
375
+ companies of the Carnegie Mellon Sphinx Speech Consortium. We acknowledge
376
+ the contributions of many volunteers to the expansion and improvement of
377
+ this dictionary.
378
+
379
+ THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND
380
+ ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
381
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
382
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY
383
+ NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
384
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
385
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
386
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
387
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
388
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
389
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
390
+ ```
wake/capture-worklet.mjs ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class WakeCapture extends AudioWorkletProcessor {
2
+ constructor(){super();this.buffer=new Int16Array(512);this.offset=0;this.active=true;
3
+ this.port.onmessage=({data})=>{if(data==='stop'){
4
+ this.active=false;
5
+ if(this.offset)this.port.postMessage({pcm:this.buffer.slice(0,this.offset)});
6
+ this.port.postMessage({stopped:true});
7
+ }};
8
+ }
9
+ process(inputs){
10
+ if(!this.active)return false;
11
+ const channel=inputs[0]?.[0];
12
+ if(channel)for(const sample of channel){
13
+ this.buffer[this.offset++]=Math.round(Math.max(-1,Math.min(1,sample))* (sample<0?32768:32767));
14
+ if(this.offset===512){const pcm=this.buffer;this.port.postMessage({pcm},[pcm.buffer]);this.buffer=new Int16Array(512);this.offset=0;}
15
+ }
16
+ return true;
17
+ }
18
+ }
19
+ registerProcessor('phonlet-wake-capture',WakeCapture);
wake/capture.d.ts ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {WakeOptions,Detection} from './index.js';
2
+ export interface CaptureOptions {
3
+ wake:WakeOptions; onDetection:(event:Detection)=>void; onError:(error:Error)=>void;
4
+ audioContext?:AudioContext; stream?:MediaStream;
5
+ }
6
+ export class WakeManager {
7
+ constructor(options:CaptureOptions);
8
+ readonly state:'idle'|'starting'|'listening'|'stopping'|'error'|'closed';
9
+ readonly lastError:Error|null;
10
+ start():Promise<void>; stop():Promise<void>; close():Promise<void>;
11
+ }
wake/capture.mjs ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {Wake,WakeError} from './index.mjs';
2
+ import {fields} from './shared.mjs';
3
+
4
+ // Serial lifecycle, bounded audio and callback delivery. Borrowed resources stay owned by the caller.
5
+ export class WakeManager {
6
+ #config; #wake; #context; #stream; #source; #node; #gain;
7
+ #ownedContext=false; #ownedStream=false; #serial=Promise.resolve(); #audio=Promise.resolve();
8
+ #queued=0; #state='idle'; #stopAck; #lastError=null; #closing=false; #closeTask; #listeners=[];
9
+ constructor(config){
10
+ fields(config,['wake','onDetection','onError'],['audioContext','stream'],'manager options');
11
+ if(typeof config.onDetection!=='function'||typeof config.onError!=='function')throw new WakeError('INVALID_ARGUMENT','onDetection and onError are required functions');
12
+ this.#config={...config,wake:{...config.wake,keywords:structuredClone(config.wake.keywords)}};
13
+ }
14
+ get state(){return this.#state;} get lastError(){return this.#lastError;}
15
+ #operation(fn){const result=this.#serial.then(fn);this.#serial=result.catch(()=>{});return result;}
16
+ #error(error){
17
+ if(this.#state==='error'||this.#state==='closed')return;
18
+ this.#lastError=error;this.#state='error';
19
+ try{this.#config.onError(error);}catch(callbackError){this.#lastError=callbackError;}
20
+ void this.stop().catch(()=>{});
21
+ }
22
+ start(){return this.#operation(async()=>{
23
+ if(this.#state==='closed'||this.#closing)throw new WakeError('INVALID_STATE','manager closed');
24
+ if(this.#state==='listening')return;
25
+ this.#state='starting';this.#lastError=null;this.#audio=Promise.resolve();this.#queued=0;
26
+ try{
27
+ this.#wake=await Wake.create(this.#config.wake);
28
+ this.#ownedContext=!this.#config.audioContext;
29
+ this.#context=this.#config.audioContext??new AudioContext({sampleRate:16000});
30
+ if(this.#context.sampleRate!==16000)throw new WakeError('AUDIO_FAILURE','Wake capture requires a 16 kHz AudioContext');
31
+ await this.#context.resume();
32
+ this.#ownedStream=!this.#config.stream;
33
+ this.#stream=this.#config.stream??await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,sampleRate:16000,echoCancellation:false,noiseSuppression:false,autoGainControl:false}});
34
+ await this.#context.audioWorklet.addModule(new URL('./capture-worklet.mjs',import.meta.url));
35
+ this.#source=this.#context.createMediaStreamSource(this.#stream);
36
+ this.#node=new AudioWorkletNode(this.#context,'phonlet-wake-capture',{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],channelCount:1,channelCountMode:'explicit'});
37
+ this.#gain=this.#context.createGain();this.#gain.gain.value=0;
38
+ this.#node.onprocessorerror=()=>this.#error(new WakeError('AUDIO_FAILURE','audio worklet failed'));
39
+ this.#node.port.onmessage=({data})=>{
40
+ if(data.stopped){this.#stopAck?.();return;}
41
+ if(!data.pcm||!['listening','stopping'].includes(this.#state))return;
42
+ const pcm=data.pcm;
43
+ if(this.#queued+pcm.length>4096){this.#error(new WakeError('OVERLOADED','capture queue exceeded 4096 samples'));return;}
44
+ this.#queued+=pcm.length;
45
+ this.#audio=this.#audio.then(async()=>{
46
+ const result=await this.#wake.process(pcm);
47
+ for(const event of result){
48
+ // Capture callbacks are synchronous so slow async delivery cannot form a second unbounded queue.
49
+ const returned=this.#config.onDetection(event);
50
+ if(returned?.then){returned.catch(()=>{});throw new WakeError('INVALID_ARGUMENT','onDetection must be synchronous');}
51
+ }
52
+ }).catch(error=>this.#error(error)).finally(()=>{this.#queued-=pcm.length;});
53
+ };
54
+ this.#source.connect(this.#node);this.#node.connect(this.#gain);this.#gain.connect(this.#context.destination);
55
+ this.#state='listening';
56
+ const listen=(target,event,handler)=>{target.addEventListener(event,handler);this.#listeners.push(()=>target.removeEventListener(event,handler));};
57
+ for(const track of this.#stream.getAudioTracks())listen(track,'ended',()=>{if(this.#state==='listening')this.#error(new WakeError('AUDIO_FAILURE','microphone track ended'));});
58
+ listen(this.#context,'statechange',()=>{if(this.#state==='listening'&&this.#context.state!=='running')this.#error(new WakeError('AUDIO_FAILURE','audio context stopped'));});
59
+ }catch(error){
60
+ this.#lastError=error;await this.#cleanup();this.#state='idle';
61
+ try{this.#config.onError(error);}catch(callbackError){this.#lastError=callbackError;}
62
+ throw error;
63
+ }
64
+ });}
65
+ async #cleanup(){
66
+ this.#listeners.forEach(remove=>remove());this.#listeners=[];
67
+ this.#source?.disconnect();this.#node?.disconnect();this.#gain?.disconnect();
68
+ if(this.#node){this.#node.port.onmessage=null;this.#node.onprocessorerror=null;this.#node.port.close();}
69
+ if(this.#ownedStream)this.#stream?.getTracks().forEach(track=>track.stop());
70
+ try{await this.#wake?.close();}finally{
71
+ if(this.#ownedContext&&this.#context&&this.#context.state!=='closed')await this.#context.close();
72
+ this.#wake=this.#context=this.#stream=this.#source=this.#node=this.#gain=null;
73
+ }
74
+ }
75
+ stop(){return this.#operation(async()=>{
76
+ if(this.#state==='idle'||this.#state==='closed')return;
77
+ const wasError=this.#state==='error';this.#state=wasError?'error':'stopping';
78
+ try{
79
+ if(this.#node&&this.#context.state==='running'&&!wasError){
80
+ await new Promise((resolve,reject)=>{
81
+ const timer=setTimeout(()=>reject(new WakeError('AUDIO_FAILURE','capture stop timed out')),2000);
82
+ this.#stopAck=()=>{clearTimeout(timer);resolve();};this.#node.port.postMessage('stop');
83
+ });
84
+ }
85
+ this.#source?.disconnect();
86
+ await this.#audio;
87
+ if(this.#wake?.state==='ready')await this.#wake.finish();
88
+ }finally{await this.#cleanup();this.#state='idle';this.#stopAck=null;}
89
+ });}
90
+ close(){
91
+ if(this.#closeTask)return this.#closeTask;
92
+ this.#closing=true;this.#closeTask=this.stop().finally(()=>{this.#state='closed';});return this.#closeTask;
93
+ }
94
+ }
wake/dist/kws_engine.mjs ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ async function createKwsModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await import("node:module");var require=createRequire(import.meta.url)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}programArgs=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["m"]();FS.ignorePermissions=false}function postRun(){}function abort(what){what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";if(runtimeInitialized){___trap()}var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("kws_engine.wasm")}return new URL("kws_engine.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPreRuns=[];var HEAP32;var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>{if(ENVIRONMENT_IS_NODE){var nodeCrypto=require("node:crypto");return view=>(nodeCrypto.randomFillSync(view),0)}return view=>(crypto.getRandomValues(view),0)};var randomFill=view=>(randomFill=initRandomFill())(view);var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc(BUFSIZE);var bytesRead=0;var fd=process.stdin.fd;try{bytesRead=fs.readSync(fd,buf,0,BUFSIZE)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}}else if(globalThis.window?.prompt){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&!bytesRead){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result;if(result===10)break}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(60)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(29)}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}},default_tty_ops:{get_char(tty){return FS_stdin_getChar()},put_char(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var mmapAlloc=size=>{abort()};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=MEMFS.emptyFileContents??=new Uint8Array(0)}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){return node.contents.subarray(0,node.usedBytes)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents.length;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)>>>0);if(prevCapacity)newCapacity=Math.max(newCapacity,256);var oldContents=MEMFS.getFileDataAsTypedArray(node);node.contents=new Uint8Array(newCapacity);node.contents.set(oldContents)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;var oldContents=node.contents;node.contents=new Uint8Array(newSize);node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)));node.usedBytes=newSize},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){if(!MEMFS.doesNotExistError){MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="<generic error, no stack>"}throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);buffer.set(contents.subarray(position,position+size),offset);return size},write(stream,buffer,offset,length,position,canOwn){if(buffer.buffer===HEAP8.buffer){canOwn=false}if(!length)return 0;var node=stream.node;node.mtime=node.ctime=Date.now();if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length}else if(!node.usedBytes&&!position){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length}else{MEMFS.expandFileStorage(node,position+length);node.contents.set(buffer.subarray(offset,offset+length),position);node.usedBytes=Math.max(node.usedBytes,position+length)}return length},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){position+=stream.node.usedBytes}}if(position<0){throw new FS.ErrnoError(28)}return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents.buffer===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}if(contents){if(position>0||position+length<contents.length){if(contents.subarray){contents=contents.subarray(position,position+length)}else{contents=Array.prototype.slice.call(contents,position,position+length)}}HEAP8.set(contents,ptr)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var FS_modeStringToFlags=str=>{if(typeof str!="string")return str;var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_fileDataToTypedArray=data=>{if(typeof data=="string"){data=intArrayFromString(data,true)}if(!data.subarray){data=new Uint8Array(data)}return data};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var getUniqueRunDependency=id=>id;var dependenciesPromise=null;var resolveRunDependencies=async()=>dependenciesPromise;var runDependencies=0;var dependenciesPromiseResolve=null;var removeRunDependency=id=>{runDependencies--;if(!runDependencies){dependenciesPromiseResolve()}};var addRunDependency=id=>{if(!runDependencies){dependenciesPromise=new Promise(resolve=>dependenciesPromiseResolve=resolve)}runDependencies++};var preloadPlugins=[];var FS_handledByPreloadPlugin=async(byteArray,fullname)=>{if(typeof Browser!="undefined")Browser.init();for(var plugin of preloadPlugins){if(plugin["canHandle"](fullname)){return plugin["handle"](byteArray,fullname)}}return byteArray};var FS_preloadFile=async(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);addRunDependency(dep);try{var byteArray=url;if(typeof url=="string"){byteArray=await asyncLoad(url)}byteArray=await FS_handledByPreloadPlugin(byteArray,fullname);preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}}finally{removeRunDependency(dep)}};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{FS_preloadFile(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish).then(onload).catch(onerror)};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}addListener(cb,exclusive=false){var entry={cb,exclusive};var listeners=this.listeners??=new Set;listeners.add(entry);return{listeners,entry}}notifyListeners(flags){if(!this.listeners)return;var excl;for(var entry of this.listeners){if(entry.exclusive)(excl||=[]).push(entry);else entry.cb(flags)}if(excl){var i=(this.exclTurn||0)%excl.length;this.exclTurn=i+1;excl[i].cb(flags)}}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i<parts.length;i++){var islast=i===parts.length-1;if(islast&&opts.parent){break}if(parts[i]==="."){continue}if(parts[i]===".."){current_path=PATH.dirname(current_path);if(FS.isRoot(current)){path=current_path+"/"+parts.slice(i+1).join("/");nlinks--;continue linkloop}else{current=current.parent}continue}current_path=PATH.join2(current_path,parts[i]);try{current=FS.lookupNode(current,parts[i])}catch(e){if(e?.errno===44&&islast&&opts.noent_okay){return{path:current_path}}throw e}if(FS.isMountpoint(current)&&(!islast||opts.follow_mount)){current=current.mounted.root}if(FS.isLink(current.mode)&&(!islast||opts.follow)){if(!current.node_ops.readlink){throw new FS.ErrnoError(52)}var link=current.node_ops.readlink(current);if(!PATH.isAbs(link)){link=PATH.dirname(current_path)+"/"+link}path=link+"/"+parts.slice(i+1).join("/");continue linkloop}}return{path:current_path,node:current}}throw new FS.ErrnoError(32)},getPath(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?`${mount}/${path}`:mount+path}path=path?`${node.name}/${path}`:node.name;node=node.parent}},hashName(parentid,name){var hash=0;for(var i=0;i<name.length;i++){hash=(hash<<5)-hash+name.charCodeAt(i)|0}return(parentid+hash>>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}if(perms.includes("w")&&!(node.mode&146)){return 2}if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else if(FS.isDir(node.mode)){return 31}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}var mode=FS.flagsToPermissionString(flags);if(FS.isDir(node.mode)){if(mode!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,mode)},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);try{setattr(arg,attr)}catch(e){if(e instanceof RangeError){throw new FS.ErrnoError(22)}throw e}},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}for(var mount of mounts){if(mount.type.syncfs){mount.type.syncfs(mount,populate,done)}else{done(null)}}},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);for(var[hash,current]of Object.entries(FS.nameTable)){while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}}node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},link(oldpath,newpath,flags){var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.link){throw new FS.ErrnoError(34)}return parent.node_ops.link(parent,newname,oldpath,flags)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});FS.doSetAttr(null,lookup.node,{atime,mtime,dontFollow})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=FS_modeStringToFlags(flags);if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;stream.node?.notifyListeners(32);try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if(prot&2&&!(flags&2)&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags??0;opts.encoding=opts.encoding??"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){abort(`Invalid encoding type "${opts.encoding}"`)}var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){buf=UTF8ArrayToString(buf)}FS.close(stream);return buf},writeFile(path,data,opts={}){opts.flags=opts.flags??577;var stream=FS.open(path,opts.flags,opts.mode);data=FS_fileDataToTypedArray(data);FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn);FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(!randomLeft){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){data=FS_fileDataToTypedArray(data);FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}},createDevice(parent,name,input,output){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(!!input,!!output);FS.createDevice.major??=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open(stream){stream.seekable=false},close(stream){if(output?.buffer?.length){output(10)}},read(stream,buffer,offset,length,pos){var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=input()}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&!bytesRead){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){for(var i=0;i<length;i++){try{output(buffer[offset+i])}catch(e){throw new FS.ErrnoError(29)}}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}});return FS.mkdev(path,mode,dev)},forceLoadFile(obj){if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(globalThis.XMLHttpRequest){abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else{try{obj.contents=readBinary(obj.url)}catch(e){throw new FS.ErrnoError(29)}}},createLazyFile(parent,name,url,canRead,canWrite){class LazyUint8Array{lengthKnown=false;chunks=[];get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort(`Couldn't load ${url}. Status: ${xhr.status}`);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)abort(`invalid range (${from}, ${to}) or no bytes requested!`);if(to>datalength-1)abort(`only ${datalength} bytes available! programmer error!`);var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range",`bytes=${from}-${to}`);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort(`Couldn't load ${url}. Status: ${xhr.status}`);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText??"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")abort("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};for(const[key,fn]of Object.entries(node.stream_ops)){stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}}function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i<size;i++){buffer[offset+i]=contents[position+i]}}else{for(var i=0;i<size;i++){buffer[offset+i]=contents.get(position+i)}}return size}stream_ops.read=(stream,buffer,offset,length,position)=>{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var HEAPU8;var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var HEAPU32;var HEAP64;var SYSCALLS={currentUmask:18,calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAPU32[buf>>2]=stat.dev;HEAPU32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAPU32[buf+12>>2]=stat.uid;HEAPU32[buf+16>>2]=stat.gid;HEAPU32[buf+20>>2]=stat.rdev;HEAP64[buf+24>>3]=BigInt(stat.size);HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();HEAP64[buf+40>>3]=BigInt(Math.floor(atime/1e3));HEAPU32[buf+48>>2]=atime%1e3*1e3*1e3;HEAP64[buf+56>>3]=BigInt(Math.floor(mtime/1e3));HEAPU32[buf+64>>2]=mtime%1e3*1e3*1e3;HEAP64[buf+72>>3]=BigInt(Math.floor(ctime/1e3));HEAPU32[buf+80>>2]=ctime%1e3*1e3*1e3;HEAP64[buf+88>>3]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){HEAPU32[buf+4>>2]=stats.bsize;HEAPU32[buf+60>>2]=stats.bsize;HEAP64[buf+8>>3]=BigInt(stats.blocks);HEAP64[buf+16>>3]=BigInt(stats.bfree);HEAP64[buf+24>>3]=BigInt(stats.bavail);HEAP64[buf+32>>3]=BigInt(stats.files);HEAP64[buf+40>>3]=BigInt(stats.ffree);HEAPU32[buf+48>>2]=stats.fsid;HEAPU32[buf+64>>2]=stats.flags;HEAPU32[buf+56>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.subarray(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};var HEAP16;function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();var mask=289792;stream.flags=stream.flags&~mask|arg&mask;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>2]=termios.c_iflag||0;HEAP32[argp+4>>2]=termios.c_oflag||0;HEAP32[argp+8>>2]=termios.c_cflag||0;HEAP32[argp+12>>2]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>2];var c_oflag=HEAP32[argp+4>>2];var c_cflag=HEAP32[argp+8>>2];var c_lflag=HEAP32[argp+12>>2];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21537:case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>1]=winsize[0];HEAP16[argp+2>>1]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;if(flags&64){mode&=~SYSCALLS.currentUmask}return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var ENV={};var getExecutableName=()=>thisProgram;var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;var envp=0;for(var string of getEnvStrings()){var ptr=environ_buf+bufSize;HEAPU32[__environ+envp>>2]=ptr;bufSize+=stringToUTF8(string,ptr,Infinity)+1;envp+=4}return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;for(var string of strings){bufSize+=lengthBytesUTF8(string)+1}HEAPU32[penviron_buf_size>>2]=bufSize;return 0};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;try{var curr=FS.read(stream,HEAP8,ptr,len,offset)}catch(e){if(ret>0&&e instanceof FS.ErrnoError&&(e.errno==6||e.errno==6)){break}throw e}if(curr<0)return-1;ret+=curr;if(curr<len)break;if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 22;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);HEAP64[newOffset>>3]=BigInt(stream.position);if(stream.getdents&&!offset&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{if(iovcnt==1){return FS.write(stream,HEAP8,HEAPU32[iov>>2],HEAPU32[iov+4>>2],offset)}var total=0;for(var i=0,p=iov;i<iovcnt;i++,p+=8){total+=HEAPU32[p+4>>2]}var view=new Uint8Array(total);var voff=0;for(var i=0;i<iovcnt;i++,iov+=8){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];view.set(HEAPU8.subarray(ptr,ptr+len),voff);voff+=len}return FS.write(stream,view,0,total,offset)};function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var HEAPU16;var HEAPF64;var FS_createPath=(...args)=>FS.createPath(...args);var FS_unlink=(...args)=>FS.unlink(...args);var FS_createLazyFile=(...args)=>FS.createLazyFile(...args);var FS_createDevice=(...args)=>FS.createDevice(...args);FS.createPreloadedFile=FS_createPreloadedFile;FS.preloadFile=FS_preloadFile;FS.staticInit();{if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"]}Module["ENV"]=ENV;Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["UTF8ToString"]=UTF8ToString;Module["stringToUTF8"]=stringToUTF8;Module["lengthBytesUTF8"]=lengthBytesUTF8;Module["FS_preloadFile"]=FS_preloadFile;Module["FS_unlink"]=FS_unlink;Module["FS_createPath"]=FS_createPath;Module["FS_createDevice"]=FS_createDevice;Module["FS"]=FS;Module["FS_createDataFile"]=FS_createDataFile;Module["FS_createLazyFile"]=FS_createLazyFile;var _kws_abi_version,_kws_frontend_id,_kws_error,_kws_cpu_kernel,_kws_language,_kws_model_load,_kws_model_load_bytes,_kws_model_tensors,_kws_model_info,_kws_scorers,_kws_model_destroy,_kws_frontend_create,_kws_frontend_destroy,_kws_frontend_reset,_kws_frontend_push,_kws_frontend_finish,_kws_detector_create,_kws_detector_create_per_keyword,_kws_detector_destroy,_kws_detector_replay_scores,_kws_detector_push,_kws_session_create,_kws_session_create_per_keyword,_kws_session_destroy,_kws_session_finish,_kws_session_push,_kws_replay_scores,_free,_malloc,___trap,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_kws_abi_version=Module["_kws_abi_version"]=wasmExports["n"];_kws_frontend_id=Module["_kws_frontend_id"]=wasmExports["o"];_kws_error=Module["_kws_error"]=wasmExports["p"];_kws_cpu_kernel=Module["_kws_cpu_kernel"]=wasmExports["q"];_kws_language=Module["_kws_language"]=wasmExports["r"];_kws_model_load=Module["_kws_model_load"]=wasmExports["s"];_kws_model_load_bytes=Module["_kws_model_load_bytes"]=wasmExports["t"];_kws_model_tensors=Module["_kws_model_tensors"]=wasmExports["u"];_kws_model_info=Module["_kws_model_info"]=wasmExports["v"];_kws_scorers=Module["_kws_scorers"]=wasmExports["w"];_kws_model_destroy=Module["_kws_model_destroy"]=wasmExports["x"];_kws_frontend_create=Module["_kws_frontend_create"]=wasmExports["y"];_kws_frontend_destroy=Module["_kws_frontend_destroy"]=wasmExports["z"];_kws_frontend_reset=Module["_kws_frontend_reset"]=wasmExports["A"];_kws_frontend_push=Module["_kws_frontend_push"]=wasmExports["B"];_kws_frontend_finish=Module["_kws_frontend_finish"]=wasmExports["C"];_kws_detector_create=Module["_kws_detector_create"]=wasmExports["D"];_kws_detector_create_per_keyword=Module["_kws_detector_create_per_keyword"]=wasmExports["E"];_kws_detector_destroy=Module["_kws_detector_destroy"]=wasmExports["F"];_kws_detector_replay_scores=Module["_kws_detector_replay_scores"]=wasmExports["G"];_kws_detector_push=Module["_kws_detector_push"]=wasmExports["H"];_kws_session_create=Module["_kws_session_create"]=wasmExports["I"];_kws_session_create_per_keyword=Module["_kws_session_create_per_keyword"]=wasmExports["J"];_kws_session_destroy=Module["_kws_session_destroy"]=wasmExports["K"];_kws_session_finish=Module["_kws_session_finish"]=wasmExports["L"];_kws_session_push=Module["_kws_session_push"]=wasmExports["M"];_kws_replay_scores=Module["_kws_replay_scores"]=wasmExports["N"];_free=Module["_free"]=wasmExports["O"];_malloc=Module["_malloc"]=wasmExports["P"];___trap=wasmExports["Q"];memory=wasmMemory=wasmExports["l"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={c:___syscall_fcntl64,i:___syscall_ioctl,k:___syscall_openat,d:__abort_js,j:_emscripten_resize_heap,f:_environ_get,g:_environ_sizes_get,a:_fd_close,h:_fd_read,e:_fd_seek,b:_fd_write};async function run(){preRun();if(runDependencies){await resolveRunDependencies()}if(ABORT)return;initRuntime();postRun()}var wasmExports;wasmExports=await createWasm();await run();
2
+ ;return Module}export default createKwsModule;
wake/dist/kws_engine.simd.mjs ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ async function createKwsModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await import("node:module");var require=createRequire(import.meta.url)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}programArgs=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["m"]();FS.ignorePermissions=false}function postRun(){}function abort(what){what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";if(runtimeInitialized){___trap()}var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("kws_engine.simd.wasm")}return new URL("kws_engine.simd.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPreRuns=[];var HEAP32;var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>{if(ENVIRONMENT_IS_NODE){var nodeCrypto=require("node:crypto");return view=>(nodeCrypto.randomFillSync(view),0)}return view=>(crypto.getRandomValues(view),0)};var randomFill=view=>(randomFill=initRandomFill())(view);var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc(BUFSIZE);var bytesRead=0;var fd=process.stdin.fd;try{bytesRead=fs.readSync(fd,buf,0,BUFSIZE)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}}else if(globalThis.window?.prompt){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&!bytesRead){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result;if(result===10)break}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(60)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(29)}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}},default_tty_ops:{get_char(tty){return FS_stdin_getChar()},put_char(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var mmapAlloc=size=>{abort()};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=MEMFS.emptyFileContents??=new Uint8Array(0)}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){return node.contents.subarray(0,node.usedBytes)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents.length;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)>>>0);if(prevCapacity)newCapacity=Math.max(newCapacity,256);var oldContents=MEMFS.getFileDataAsTypedArray(node);node.contents=new Uint8Array(newCapacity);node.contents.set(oldContents)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;var oldContents=node.contents;node.contents=new Uint8Array(newSize);node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)));node.usedBytes=newSize},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){if(!MEMFS.doesNotExistError){MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="<generic error, no stack>"}throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);buffer.set(contents.subarray(position,position+size),offset);return size},write(stream,buffer,offset,length,position,canOwn){if(buffer.buffer===HEAP8.buffer){canOwn=false}if(!length)return 0;var node=stream.node;node.mtime=node.ctime=Date.now();if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length}else if(!node.usedBytes&&!position){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length}else{MEMFS.expandFileStorage(node,position+length);node.contents.set(buffer.subarray(offset,offset+length),position);node.usedBytes=Math.max(node.usedBytes,position+length)}return length},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){position+=stream.node.usedBytes}}if(position<0){throw new FS.ErrnoError(28)}return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents.buffer===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}if(contents){if(position>0||position+length<contents.length){if(contents.subarray){contents=contents.subarray(position,position+length)}else{contents=Array.prototype.slice.call(contents,position,position+length)}}HEAP8.set(contents,ptr)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var FS_modeStringToFlags=str=>{if(typeof str!="string")return str;var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_fileDataToTypedArray=data=>{if(typeof data=="string"){data=intArrayFromString(data,true)}if(!data.subarray){data=new Uint8Array(data)}return data};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var getUniqueRunDependency=id=>id;var dependenciesPromise=null;var resolveRunDependencies=async()=>dependenciesPromise;var runDependencies=0;var dependenciesPromiseResolve=null;var removeRunDependency=id=>{runDependencies--;if(!runDependencies){dependenciesPromiseResolve()}};var addRunDependency=id=>{if(!runDependencies){dependenciesPromise=new Promise(resolve=>dependenciesPromiseResolve=resolve)}runDependencies++};var preloadPlugins=[];var FS_handledByPreloadPlugin=async(byteArray,fullname)=>{if(typeof Browser!="undefined")Browser.init();for(var plugin of preloadPlugins){if(plugin["canHandle"](fullname)){return plugin["handle"](byteArray,fullname)}}return byteArray};var FS_preloadFile=async(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);addRunDependency(dep);try{var byteArray=url;if(typeof url=="string"){byteArray=await asyncLoad(url)}byteArray=await FS_handledByPreloadPlugin(byteArray,fullname);preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}}finally{removeRunDependency(dep)}};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{FS_preloadFile(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish).then(onload).catch(onerror)};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}addListener(cb,exclusive=false){var entry={cb,exclusive};var listeners=this.listeners??=new Set;listeners.add(entry);return{listeners,entry}}notifyListeners(flags){if(!this.listeners)return;var excl;for(var entry of this.listeners){if(entry.exclusive)(excl||=[]).push(entry);else entry.cb(flags)}if(excl){var i=(this.exclTurn||0)%excl.length;this.exclTurn=i+1;excl[i].cb(flags)}}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i<parts.length;i++){var islast=i===parts.length-1;if(islast&&opts.parent){break}if(parts[i]==="."){continue}if(parts[i]===".."){current_path=PATH.dirname(current_path);if(FS.isRoot(current)){path=current_path+"/"+parts.slice(i+1).join("/");nlinks--;continue linkloop}else{current=current.parent}continue}current_path=PATH.join2(current_path,parts[i]);try{current=FS.lookupNode(current,parts[i])}catch(e){if(e?.errno===44&&islast&&opts.noent_okay){return{path:current_path}}throw e}if(FS.isMountpoint(current)&&(!islast||opts.follow_mount)){current=current.mounted.root}if(FS.isLink(current.mode)&&(!islast||opts.follow)){if(!current.node_ops.readlink){throw new FS.ErrnoError(52)}var link=current.node_ops.readlink(current);if(!PATH.isAbs(link)){link=PATH.dirname(current_path)+"/"+link}path=link+"/"+parts.slice(i+1).join("/");continue linkloop}}return{path:current_path,node:current}}throw new FS.ErrnoError(32)},getPath(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?`${mount}/${path}`:mount+path}path=path?`${node.name}/${path}`:node.name;node=node.parent}},hashName(parentid,name){var hash=0;for(var i=0;i<name.length;i++){hash=(hash<<5)-hash+name.charCodeAt(i)|0}return(parentid+hash>>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}if(perms.includes("w")&&!(node.mode&146)){return 2}if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else if(FS.isDir(node.mode)){return 31}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}var mode=FS.flagsToPermissionString(flags);if(FS.isDir(node.mode)){if(mode!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,mode)},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);try{setattr(arg,attr)}catch(e){if(e instanceof RangeError){throw new FS.ErrnoError(22)}throw e}},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}for(var mount of mounts){if(mount.type.syncfs){mount.type.syncfs(mount,populate,done)}else{done(null)}}},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);for(var[hash,current]of Object.entries(FS.nameTable)){while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}}node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},link(oldpath,newpath,flags){var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.link){throw new FS.ErrnoError(34)}return parent.node_ops.link(parent,newname,oldpath,flags)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});FS.doSetAttr(null,lookup.node,{atime,mtime,dontFollow})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=FS_modeStringToFlags(flags);if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;stream.node?.notifyListeners(32);try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if(prot&2&&!(flags&2)&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags??0;opts.encoding=opts.encoding??"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){abort(`Invalid encoding type "${opts.encoding}"`)}var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){buf=UTF8ArrayToString(buf)}FS.close(stream);return buf},writeFile(path,data,opts={}){opts.flags=opts.flags??577;var stream=FS.open(path,opts.flags,opts.mode);data=FS_fileDataToTypedArray(data);FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn);FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(!randomLeft){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){data=FS_fileDataToTypedArray(data);FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}},createDevice(parent,name,input,output){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(!!input,!!output);FS.createDevice.major??=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open(stream){stream.seekable=false},close(stream){if(output?.buffer?.length){output(10)}},read(stream,buffer,offset,length,pos){var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=input()}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&!bytesRead){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){for(var i=0;i<length;i++){try{output(buffer[offset+i])}catch(e){throw new FS.ErrnoError(29)}}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}});return FS.mkdev(path,mode,dev)},forceLoadFile(obj){if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(globalThis.XMLHttpRequest){abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else{try{obj.contents=readBinary(obj.url)}catch(e){throw new FS.ErrnoError(29)}}},createLazyFile(parent,name,url,canRead,canWrite){class LazyUint8Array{lengthKnown=false;chunks=[];get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort(`Couldn't load ${url}. Status: ${xhr.status}`);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)abort(`invalid range (${from}, ${to}) or no bytes requested!`);if(to>datalength-1)abort(`only ${datalength} bytes available! programmer error!`);var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range",`bytes=${from}-${to}`);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort(`Couldn't load ${url}. Status: ${xhr.status}`);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText??"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")abort("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};for(const[key,fn]of Object.entries(node.stream_ops)){stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}}function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i<size;i++){buffer[offset+i]=contents[position+i]}}else{for(var i=0;i<size;i++){buffer[offset+i]=contents.get(position+i)}}return size}stream_ops.read=(stream,buffer,offset,length,position)=>{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var HEAPU8;var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var HEAPU32;var HEAP64;var SYSCALLS={currentUmask:18,calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAPU32[buf>>2]=stat.dev;HEAPU32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAPU32[buf+12>>2]=stat.uid;HEAPU32[buf+16>>2]=stat.gid;HEAPU32[buf+20>>2]=stat.rdev;HEAP64[buf+24>>3]=BigInt(stat.size);HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();HEAP64[buf+40>>3]=BigInt(Math.floor(atime/1e3));HEAPU32[buf+48>>2]=atime%1e3*1e3*1e3;HEAP64[buf+56>>3]=BigInt(Math.floor(mtime/1e3));HEAPU32[buf+64>>2]=mtime%1e3*1e3*1e3;HEAP64[buf+72>>3]=BigInt(Math.floor(ctime/1e3));HEAPU32[buf+80>>2]=ctime%1e3*1e3*1e3;HEAP64[buf+88>>3]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){HEAPU32[buf+4>>2]=stats.bsize;HEAPU32[buf+60>>2]=stats.bsize;HEAP64[buf+8>>3]=BigInt(stats.blocks);HEAP64[buf+16>>3]=BigInt(stats.bfree);HEAP64[buf+24>>3]=BigInt(stats.bavail);HEAP64[buf+32>>3]=BigInt(stats.files);HEAP64[buf+40>>3]=BigInt(stats.ffree);HEAPU32[buf+48>>2]=stats.fsid;HEAPU32[buf+64>>2]=stats.flags;HEAPU32[buf+56>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.subarray(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};var HEAP16;function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();var mask=289792;stream.flags=stream.flags&~mask|arg&mask;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>2]=termios.c_iflag||0;HEAP32[argp+4>>2]=termios.c_oflag||0;HEAP32[argp+8>>2]=termios.c_cflag||0;HEAP32[argp+12>>2]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>2];var c_oflag=HEAP32[argp+4>>2];var c_cflag=HEAP32[argp+8>>2];var c_lflag=HEAP32[argp+12>>2];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21537:case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>1]=winsize[0];HEAP16[argp+2>>1]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;if(flags&64){mode&=~SYSCALLS.currentUmask}return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var ENV={};var getExecutableName=()=>thisProgram;var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;var envp=0;for(var string of getEnvStrings()){var ptr=environ_buf+bufSize;HEAPU32[__environ+envp>>2]=ptr;bufSize+=stringToUTF8(string,ptr,Infinity)+1;envp+=4}return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;for(var string of strings){bufSize+=lengthBytesUTF8(string)+1}HEAPU32[penviron_buf_size>>2]=bufSize;return 0};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;try{var curr=FS.read(stream,HEAP8,ptr,len,offset)}catch(e){if(ret>0&&e instanceof FS.ErrnoError&&(e.errno==6||e.errno==6)){break}throw e}if(curr<0)return-1;ret+=curr;if(curr<len)break;if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 22;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);HEAP64[newOffset>>3]=BigInt(stream.position);if(stream.getdents&&!offset&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{if(iovcnt==1){return FS.write(stream,HEAP8,HEAPU32[iov>>2],HEAPU32[iov+4>>2],offset)}var total=0;for(var i=0,p=iov;i<iovcnt;i++,p+=8){total+=HEAPU32[p+4>>2]}var view=new Uint8Array(total);var voff=0;for(var i=0;i<iovcnt;i++,iov+=8){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];view.set(HEAPU8.subarray(ptr,ptr+len),voff);voff+=len}return FS.write(stream,view,0,total,offset)};function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var HEAPU16;var HEAPF64;var FS_createPath=(...args)=>FS.createPath(...args);var FS_unlink=(...args)=>FS.unlink(...args);var FS_createLazyFile=(...args)=>FS.createLazyFile(...args);var FS_createDevice=(...args)=>FS.createDevice(...args);FS.createPreloadedFile=FS_createPreloadedFile;FS.preloadFile=FS_preloadFile;FS.staticInit();{if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"]}Module["ENV"]=ENV;Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["UTF8ToString"]=UTF8ToString;Module["stringToUTF8"]=stringToUTF8;Module["lengthBytesUTF8"]=lengthBytesUTF8;Module["FS_preloadFile"]=FS_preloadFile;Module["FS_unlink"]=FS_unlink;Module["FS_createPath"]=FS_createPath;Module["FS_createDevice"]=FS_createDevice;Module["FS"]=FS;Module["FS_createDataFile"]=FS_createDataFile;Module["FS_createLazyFile"]=FS_createLazyFile;var _kws_abi_version,_kws_frontend_id,_kws_error,_kws_cpu_kernel,_kws_language,_kws_model_load,_kws_model_load_bytes,_kws_model_tensors,_kws_model_info,_kws_scorers,_kws_model_destroy,_kws_frontend_create,_kws_frontend_destroy,_kws_frontend_reset,_kws_frontend_push,_kws_frontend_finish,_kws_detector_create,_kws_detector_create_per_keyword,_kws_detector_destroy,_kws_detector_replay_scores,_kws_detector_push,_kws_session_create,_kws_session_create_per_keyword,_kws_session_destroy,_kws_session_finish,_kws_session_push,_kws_replay_scores,_free,_malloc,___trap,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_kws_abi_version=Module["_kws_abi_version"]=wasmExports["n"];_kws_frontend_id=Module["_kws_frontend_id"]=wasmExports["o"];_kws_error=Module["_kws_error"]=wasmExports["p"];_kws_cpu_kernel=Module["_kws_cpu_kernel"]=wasmExports["q"];_kws_language=Module["_kws_language"]=wasmExports["r"];_kws_model_load=Module["_kws_model_load"]=wasmExports["s"];_kws_model_load_bytes=Module["_kws_model_load_bytes"]=wasmExports["t"];_kws_model_tensors=Module["_kws_model_tensors"]=wasmExports["u"];_kws_model_info=Module["_kws_model_info"]=wasmExports["v"];_kws_scorers=Module["_kws_scorers"]=wasmExports["w"];_kws_model_destroy=Module["_kws_model_destroy"]=wasmExports["x"];_kws_frontend_create=Module["_kws_frontend_create"]=wasmExports["y"];_kws_frontend_destroy=Module["_kws_frontend_destroy"]=wasmExports["z"];_kws_frontend_reset=Module["_kws_frontend_reset"]=wasmExports["A"];_kws_frontend_push=Module["_kws_frontend_push"]=wasmExports["B"];_kws_frontend_finish=Module["_kws_frontend_finish"]=wasmExports["C"];_kws_detector_create=Module["_kws_detector_create"]=wasmExports["D"];_kws_detector_create_per_keyword=Module["_kws_detector_create_per_keyword"]=wasmExports["E"];_kws_detector_destroy=Module["_kws_detector_destroy"]=wasmExports["F"];_kws_detector_replay_scores=Module["_kws_detector_replay_scores"]=wasmExports["G"];_kws_detector_push=Module["_kws_detector_push"]=wasmExports["H"];_kws_session_create=Module["_kws_session_create"]=wasmExports["I"];_kws_session_create_per_keyword=Module["_kws_session_create_per_keyword"]=wasmExports["J"];_kws_session_destroy=Module["_kws_session_destroy"]=wasmExports["K"];_kws_session_finish=Module["_kws_session_finish"]=wasmExports["L"];_kws_session_push=Module["_kws_session_push"]=wasmExports["M"];_kws_replay_scores=Module["_kws_replay_scores"]=wasmExports["N"];_free=Module["_free"]=wasmExports["O"];_malloc=Module["_malloc"]=wasmExports["P"];___trap=wasmExports["Q"];memory=wasmMemory=wasmExports["l"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={c:___syscall_fcntl64,i:___syscall_ioctl,k:___syscall_openat,d:__abort_js,j:_emscripten_resize_heap,f:_environ_get,g:_environ_sizes_get,a:_fd_close,h:_fd_read,e:_fd_seek,b:_fd_write};async function run(){preRun();if(runDependencies){await resolveRunDependencies()}if(ABORT)return;initRuntime();postRun()}var wasmExports;wasmExports=await createWasm();await run();
2
+ ;return Module}export default createKwsModule;
wake/dist/kws_engine.simd.wasm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9fc0b1ff64a5ba69675457bf1df0c5effa7ffcd7f5e4c8d3f2d2792b2ceacd99
3
+ size 311612
wake/dist/kws_engine.wasm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:963195456e6814b022885717d766e049cea424baace2b69d19be2551216a4737
3
+ size 303870
wake/index.d.ts ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export type KeywordMode = 'independent' | 'production_arbitrated';
2
+ export interface Detection {
3
+ readonly keywordId: string; readonly keyword: string; readonly keywordIndex: number;
4
+ readonly frameIndex: number; readonly sampleIndex: number; readonly timeSeconds: number; readonly sensitivity: number;
5
+ }
6
+ export interface FinishResult {readonly frames: number; readonly discardedSamples: number}
7
+ /** One phrase with its pronunciations and calibrated thresholds, as in a keyword file. */
8
+ export interface Phrase {
9
+ name: string; pronunciations: readonly (readonly number[])[]; threshold_loose: number; threshold_strict: number; endpoint: boolean;
10
+ id?: string; metadata?: Readonly<Record<string, unknown>>; sensitivity?: number;
11
+ }
12
+ /** What the threshold generator writes; "model" binds the phrases to one model by SHA-256. */
13
+ export interface KeywordFile {
14
+ model?: Readonly<{id: string; sha256: string}>; keywords: readonly Phrase[]; metadata?: Readonly<Record<string, unknown>>;
15
+ }
16
+ export class WakeError extends Error {constructor(code:string,message:string); readonly code: string}
17
+ /** A model (URL or bytes) and its phrases: a keyword file URL, the parsed keyword file, or a list of phrases. */
18
+ export interface WakeOptions {
19
+ model: string | URL | Uint8Array | ArrayBuffer; keywords: string | URL | KeywordFile | readonly Phrase[];
20
+ sensitivity?: number; keywordMode?: KeywordMode; simd?: boolean;
21
+ }
22
+ export class Wake {
23
+ private constructor();
24
+ static create(options: WakeOptions): Promise<Wake>;
25
+ readonly sampleRate: 16000; readonly frameLength: 512;
26
+ readonly state: 'starting' | 'ready' | 'finishing' | 'finished' | 'closing' | 'closed';
27
+ readonly keywords: readonly Readonly<{id: string; name: string; sensitivity: number}>[];
28
+ readonly info: Readonly<{sdkVersion:string; engineAbi:number; engineSha256:string; keywordsSha256:string; keywordMode:KeywordMode; scorer:string; scorerOptions:string; backend:string; modelSha256:string; inventoryId:string; frontendId:string}>;
29
+ process(pcm: Int16Array): Promise<readonly Detection[]>;
30
+ finish(): Promise<FinishResult>;
31
+ close(): Promise<void>;
32
+ }
33
+ export function readWav(bytes: Uint8Array): Int16Array;
wake/index.mjs ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {WakeError, options, selectPhrases, digest, pcm, freeze} from './shared.mjs';
2
+ export {WakeError, readWav} from './shared.mjs';
3
+
4
+ // Bytes from a URL (relative to the page), or a copy of bytes the caller passed.
5
+ async function bytes(value, label) {
6
+ if (value instanceof Uint8Array) return new Uint8Array(value);
7
+ if (value instanceof ArrayBuffer) return new Uint8Array(value.slice(0));
8
+ if (typeof value !== 'string' && !(value instanceof URL)) throw new WakeError('INVALID_ARGUMENT', `${label} must be a URL or bytes`);
9
+ const response = await fetch(value);
10
+ if (!response.ok) throw new WakeError('CORRUPT_ARTIFACT', `cannot load ${label}: HTTP ${response.status}`);
11
+ return new Uint8Array(await response.arrayBuffer());
12
+ }
13
+ // A keyword file from a URL; a parsed file or a list of phrases passes through.
14
+ async function keywordFile(value) {
15
+ if (typeof value !== 'string' && !(value instanceof URL)) return value;
16
+ try { return JSON.parse(new TextDecoder().decode(await bytes(value, 'keyword file'))); }
17
+ catch (error) { if (error instanceof WakeError) throw error; throw new WakeError('CORRUPT_ARTIFACT', `keyword file is not valid JSON: ${error.message}`); }
18
+ }
19
+
20
+ export class Wake {
21
+ #worker; #requests=new Map(); #sequence=0; #queued=0; #state='starting';
22
+ #selected; #info; #final; #finishTask; #closeTask;
23
+ constructor(token,worker,selected) {
24
+ if(token!==Wake) throw new WakeError('INVALID_ARGUMENT','use Wake.create');
25
+ this.#worker=worker;this.#selected=selected;
26
+ worker.onmessage=({data})=>{
27
+ const pending=this.#requests.get(data.id);if(!pending)return;
28
+ this.#requests.delete(data.id);clearTimeout(pending.timer);
29
+ if(data.error)pending.reject(new WakeError(data.error.code??'ENGINE_FAILURE',data.error.message));
30
+ else pending.resolve(data.result);
31
+ };
32
+ worker.onerror=e=>{e.preventDefault();this.#fail(new WakeError('ENGINE_FAILURE',e.message||'Wake worker failed'));};
33
+ worker.onmessageerror=()=>this.#fail(new WakeError('ENGINE_FAILURE','invalid worker message'));
34
+ }
35
+ #fail(error){
36
+ this.#state='closed';this.#worker.terminate();
37
+ for(const p of this.#requests.values()){clearTimeout(p.timer);p.reject(error);}this.#requests.clear();
38
+ }
39
+ #rpc(operation,args,transfer=[]){
40
+ const id=++this.#sequence;
41
+ return new Promise((resolve,reject)=>{
42
+ const timer=setTimeout(()=>this.#fail(new WakeError('ENGINE_FAILURE',`worker ${operation} timed out`)),30000);
43
+ this.#requests.set(id,{resolve,reject,timer});
44
+ try{this.#worker.postMessage({id,operation,args},transfer);}
45
+ catch(error){clearTimeout(timer);this.#requests.delete(id);reject(error);}
46
+ });
47
+ }
48
+ // A model (URL or bytes) and its phrases: a keyword file URL, the parsed keyword file, or a list
49
+ // of phrases written in code. A keyword file that names its model must name this one.
50
+ static async create(input){
51
+ const {mode,defaultValue}=options(input,['simd']);
52
+ if(Object.hasOwn(input,'simd')&&typeof input.simd!=='boolean')throw new WakeError('INVALID_ARGUMENT','simd must be boolean');
53
+ const model=await bytes(input.model,'model');
54
+ const selected=selectPhrases(await keywordFile(input.keywords),await digest(model),defaultValue);
55
+ const worker=new Worker(new URL('./worker.mjs',import.meta.url),{type:'module',name:'phonlet-wake'});
56
+ const wake=new Wake(Wake,worker,selected);
57
+ try{
58
+ wake.#info=freeze(await wake.#rpc('create',{model,keywords:selected,mode,simd:input.simd??false},[model.buffer]));
59
+ wake.#state='ready';return wake;
60
+ }catch(error){wake.#fail(error);throw error;}
61
+ }
62
+ get sampleRate(){return 16000;} get frameLength(){return 512;} get state(){return this.#state;}
63
+ get keywords(){return this.#selected;} get info(){return this.#info;}
64
+ async process(input){
65
+ if(this.#state!=='ready')throw new WakeError('INVALID_STATE',`Wake is ${this.#state}`);
66
+ pcm(input);
67
+ if(input.length+this.#queued>4096)throw new WakeError('OVERLOADED','Maximum unacknowledged audio is 4096 samples; split and await file chunks.');
68
+ const count=input.length,copy=new Int16Array(input);this.#queued+=count;
69
+ try{return (await this.#rpc('process',copy,[copy.buffer])).map(freeze);}
70
+ catch(error){this.#fail(error);throw error;}
71
+ finally{this.#queued-=count;}
72
+ }
73
+ async finish(){
74
+ if(this.#state==='closed'||this.#state==='closing')throw new WakeError('INVALID_STATE',`Wake is ${this.#state}`);
75
+ if(this.#final)return this.#final;
76
+ if(!this.#finishTask){
77
+ this.#state='finishing';
78
+ this.#finishTask=this.#rpc('finish').then(result=>{
79
+ this.#final=freeze(result);if(this.#state==='finishing')this.#state='finished';return this.#final;
80
+ }).catch(error=>{this.#fail(error);throw error;});
81
+ }
82
+ return this.#finishTask;
83
+ }
84
+ async close(){
85
+ if(this.#closeTask)return this.#closeTask;
86
+ if(this.#state==='closed')return;
87
+ this.#state='closing';
88
+ this.#closeTask=this.#rpc('close').finally(()=>{this.#state='closed';this.#worker.terminate();});
89
+ return this.#closeTask;
90
+ }
91
+ }
wake/js/bindings.mjs ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Typed call layer over the raw wasm exports.
3
+ *
4
+ * Emscripten maps C `int64_t` to BigInt, so every int64 argument has to be
5
+ * converted on the way in and every int64 return on the way out. Doing that at
6
+ * each call site invites a silently wrong cast, so the signatures live in one
7
+ * table - the same declarations as src/kws_runtime/_ffi.py, in the same order.
8
+ *
9
+ * Codes: p pointer, i int32, u uint32, q int64 (BigInt at the boundary),
10
+ * s NUL-terminated string return, v void.
11
+ */
12
+
13
+ export const SIGNATURES = {
14
+ abi_version: ['u', []],
15
+ frontend_id: ['u', []],
16
+ error: ['s', []],
17
+ cpu_kernel: ['s', []],
18
+ language: ['s', ['p']],
19
+ model_load: ['p', ['p', 'p']],
20
+ model_tensors: ['p', ['u', 'p', 'p', 'q', 'p']],
21
+ model_load_bytes: ['p', ['p', 'q', 'p']],
22
+ session_create_per_keyword: ['p', ['p', 'p', 'p', 'q', 'i']],
23
+ detector_create_per_keyword: ['p', ['p', 'p', 'q', 'i', 'i', 'p']],
24
+ model_destroy: ['v', ['p']],
25
+ frontend_create: ['p', []],
26
+ frontend_destroy: ['v', ['p']],
27
+ frontend_reset: ['i', ['p']],
28
+ frontend_push: ['q', ['p', 'p', 'q', 'p', 'q']],
29
+ frontend_finish: ['q', ['p', 'i', 'p']],
30
+ detector_create: ['p', ['p', 'p', 'q', 'i', 'i', 'p']],
31
+ detector_destroy: ['v', ['p']],
32
+ detector_replay_scores: ['i', ['p', 'p', 'q', 'p']],
33
+ detector_push: ['i', ['p', 'p', 'q', 'p', 'p', 'p', 'p', 'p']],
34
+ session_create: ['p', ['p', 'p', 'p', 'q', 'i']],
35
+ session_destroy: ['v', ['p']],
36
+ session_finish: ['q', ['p']],
37
+ session_push: ['q', ['p', 'p', 'q', 'i', 'q', 'p', 'p', 'p', 'p', 'p', 'p']],
38
+ replay_scores: ['i', ['p', 'q', 'q', 'p', 'q', 'i', 'p']],
39
+ };
40
+
41
+ export function bind(module) {
42
+ const api = {};
43
+ for (const [name, [returns, takes]] of Object.entries(SIGNATURES)) {
44
+ const raw = module[`_kws_${name}`];
45
+ if (typeof raw !== 'function') throw new Error(`wasm export missing: kws_${name}`);
46
+ api[name] = (...args) => {
47
+ if (args.length !== takes.length) {
48
+ throw new Error(`kws_${name} expects ${takes.length} arguments, got ${args.length}`);
49
+ }
50
+ const marshalled = args.map((value, i) => (takes[i] === 'q' ? BigInt(value) : value));
51
+ const result = raw(...marshalled);
52
+ if (returns === 'q') return Number(result);
53
+ if (returns === 's') return result ? module.UTF8ToString(result) : null;
54
+ return result;
55
+ };
56
+ }
57
+ return api;
58
+ }
wake/js/kws.mjs ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * JavaScript bindings for the kws engine compiled to WebAssembly.
3
+ *
4
+ * The shape deliberately mirrors src/kws_runtime (Model / Frontend / Session)
5
+ * so a parity failure points at the C++ or the build flags rather than at a
6
+ * divergence invented here. Semantics that matter are inherited, not
7
+ * reimplemented: 256-sample frontend hops, 512-sample model frames, PCM tails
8
+ * retained across pushes, finish() dropping the tail without padding EOF.
9
+ */
10
+
11
+ import { bind } from './bindings.mjs';
12
+
13
+ export const SENSITIVITIES = [0.0, 0.25, 0.5, 0.75, 1.0];
14
+ const MODES = { independent: 0, production_arbitrated: 1 };
15
+
16
+ function fail(rt) {
17
+ return new Error(rt.fn.error() || 'kws: unknown error');
18
+ }
19
+
20
+ /** Null and negative both mean failure across this ABI. */
21
+ function checked(rt, value) {
22
+ if (!value || value < 0) throw fail(rt);
23
+ return value;
24
+ }
25
+
26
+ /** A malloc arena freed as a unit, so no early return can leak. */
27
+ class Scratch {
28
+ constructor(rt) {
29
+ this.rt = rt;
30
+ this.pointers = new Set();
31
+ }
32
+
33
+ alloc(bytes) {
34
+ if (bytes <= 0) return 0;
35
+ const pointer = this.rt.module._malloc(bytes);
36
+ if (!pointer) throw new Error(`out of wasm memory (${bytes} bytes)`);
37
+ this.pointers.add(pointer);
38
+ return pointer;
39
+ }
40
+
41
+ string(value) {
42
+ if (value === null || value === undefined) return 0;
43
+ const bytes = this.rt.module.lengthBytesUTF8(value) + 1;
44
+ const pointer = this.alloc(bytes);
45
+ this.rt.module.stringToUTF8(value, pointer, bytes);
46
+ return pointer;
47
+ }
48
+
49
+ /** Copies a typed array into the heap. Heap views are invalidated by memory
50
+ * growth, so the view is taken after the allocation, never cached. */
51
+ typed(array) {
52
+ const pointer = this.alloc(array.byteLength);
53
+ new Uint8Array(this.rt.module.HEAPU8.buffer, pointer, array.byteLength)
54
+ .set(new Uint8Array(array.buffer, array.byteOffset, array.byteLength));
55
+ return pointer;
56
+ }
57
+
58
+ free() {
59
+ for (const pointer of this.pointers) this.rt.module._free(pointer);
60
+ this.pointers.clear();
61
+ }
62
+ }
63
+
64
+ class Handle {
65
+ constructor(rt, pointer, destroy) {
66
+ this.rt = rt;
67
+ this.pointer = pointer;
68
+ this.destroyer = destroy;
69
+ }
70
+
71
+ check() {
72
+ if (!this.pointer) throw new Error(`${this.constructor.name} is closed`);
73
+ }
74
+
75
+ close() {
76
+ if (this.pointer) {
77
+ this.rt.fn[this.destroyer](this.pointer);
78
+ this.pointer = 0;
79
+ }
80
+ }
81
+ }
82
+
83
+ export class Model extends Handle {
84
+ constructor(rt, pointer, { language, nClasses, identity }) {
85
+ super(rt, pointer, 'model_destroy');
86
+ this.language = language;
87
+ this.nClasses = nClasses;
88
+ this.identity = identity;
89
+ }
90
+ }
91
+
92
+ export class Frontend extends Handle {
93
+ constructor(rt) {
94
+ super(rt, checked(rt, rt.fn.frontend_create()), 'frontend_destroy');
95
+ this.pending = 0;
96
+ }
97
+
98
+ reset() {
99
+ this.check();
100
+ if (this.rt.fn.frontend_reset(this.pointer) < 0) throw fail(this.rt);
101
+ this.pending = 0;
102
+ }
103
+
104
+ /** @param {Int16Array} pcm @returns {Int16Array} hops * 40 mel values */
105
+ push(pcm) {
106
+ this.check();
107
+ const hops = Math.floor((this.pending + pcm.length) / 256);
108
+ const scratch = new Scratch(this.rt);
109
+ try {
110
+ const input = scratch.typed(pcm);
111
+ const output = scratch.alloc(hops * 40 * 2);
112
+ const written = this.rt.fn.frontend_push(this.pointer, input, pcm.length, output, hops);
113
+ if (written < 0) throw fail(this.rt);
114
+ this.pending = (this.pending + pcm.length) % 256;
115
+ return this.rt.module.HEAP16.slice(output / 2, output / 2 + written * 40);
116
+ } finally {
117
+ scratch.free();
118
+ }
119
+ }
120
+
121
+ /** finalize: 'complete_hops' discards the tail, 'training_nearest_hop' pads
122
+ * a tail of at least 128 samples. */
123
+ finish(finalize = 'complete_hops') {
124
+ this.check();
125
+ if (finalize !== 'complete_hops' && finalize !== 'training_nearest_hop') {
126
+ throw new Error('unknown frontend finalization policy');
127
+ }
128
+ const scratch = new Scratch(this.rt);
129
+ try {
130
+ const output = scratch.alloc(40 * 2);
131
+ const hops = this.rt.fn.frontend_finish(
132
+ this.pointer, finalize === 'training_nearest_hop' ? 1 : 0, output,
133
+ );
134
+ if (hops < 0) throw fail(this.rt);
135
+ this.pending = 0;
136
+ return this.rt.module.HEAP16.slice(output / 2, output / 2 + hops * 40);
137
+ } finally {
138
+ scratch.free();
139
+ }
140
+ }
141
+ }
142
+
143
+ export class Session extends Handle {
144
+ constructor(rt, model, {
145
+ keywords = [], sensitivities = SENSITIVITIES, keywordSensitivities = null, mode = 'independent', outputs = null,
146
+ } = {}) {
147
+ if (!(mode in MODES)) throw new Error('mode must be independent or production_arbitrated');
148
+ model.check();
149
+ const perKeyword = keywordSensitivities !== null;
150
+ if (perKeyword && sensitivities !== SENSITIVITIES) throw new Error('select one sensitivity layout');
151
+ if (perKeyword && (!Array.isArray(keywordSensitivities) || keywordSensitivities.length !== keywords.length ||
152
+ keywordSensitivities.some(s => typeof s !== 'number' || !Number.isFinite(s)))) throw new Error('invalid per-keyword sensitivities');
153
+ const sens = Float64Array.from(perKeyword ? keywordSensitivities : sensitivities);
154
+ if (!sens.length || sens.some((s) => !(s >= 0 && s <= 1))) {
155
+ throw new Error('sensitivities must be a nonempty vector in [0,1]');
156
+ }
157
+ const scratch = new Scratch(rt);
158
+ let pointer;
159
+ try {
160
+ pointer = checked(rt, (perKeyword ? rt.fn.session_create_per_keyword : rt.fn.session_create)(
161
+ model.pointer,
162
+ keywords.length ? scratch.string(JSON.stringify(keywords)) : 0,
163
+ scratch.typed(sens),
164
+ sens.length,
165
+ MODES[mode],
166
+ ));
167
+ } finally {
168
+ scratch.free();
169
+ }
170
+ super(rt, pointer, 'session_destroy');
171
+ this.model = model;
172
+ this.keywords = keywords;
173
+ this.sensitivities = sens;
174
+ this.perKeyword = perKeyword;
175
+ this.mode = MODES[mode];
176
+ this.outputs = outputs ?? {
177
+ posteriors: !keywords.length,
178
+ events: keywords.length > 0,
179
+ scores: keywords.length > 0,
180
+ rawScores: false,
181
+ gates: false,
182
+ };
183
+ this.offset = 0;
184
+ this.pending = 0;
185
+ this.finished = false;
186
+ }
187
+
188
+ pushPcm(pcm) { return this.push(pcm, false); }
189
+
190
+ pushMel(mel) { return this.push(mel, true); }
191
+
192
+ push(input, cachedMel = false) {
193
+ this.check();
194
+ if (!(input instanceof Int16Array)) throw new TypeError('expected Int16Array');
195
+ if (this.finished) throw new Error('session finished');
196
+ const k = this.keywords.length;
197
+ const s = this.perKeyword ? 1 : this.sensitivities.length;
198
+ const want = k ? this.outputs : { ...this.outputs, events: false };
199
+ const frames = cachedMel
200
+ ? input.length / 80
201
+ : Math.floor((this.pending + input.length) / 512);
202
+ if (cachedMel && !Number.isInteger(frames)) throw new Error('expected [T,80] mel');
203
+
204
+ const scratch = new Scratch(this.rt);
205
+ try {
206
+ const pcm = scratch.typed(input);
207
+ const q31 = want.posteriors ? scratch.alloc(frames * this.model.nClasses * 4) : 0;
208
+ const resets = scratch.alloc(Math.max(frames, 1));
209
+ const scores = want.scores && k ? scratch.alloc(frames * k * 2) : 0;
210
+ const raw = want.rawScores && k ? scratch.alloc(frames * k * 2) : 0;
211
+ const fires = want.events && k ? scratch.alloc(frames * s * k) : 0;
212
+ const gates = want.gates && k ? scratch.alloc(Math.max(frames, 1)) : 0;
213
+
214
+ const count = this.rt.fn.session_push(
215
+ this.pointer, pcm, input.length, cachedMel ? 1 : 0, frames,
216
+ q31, resets, scores, raw, fires, gates,
217
+ );
218
+ if (count < 0) throw fail(this.rt);
219
+
220
+ const { HEAP16, HEAP32, HEAPU8 } = this.rt.module;
221
+ const resetFrames = [];
222
+ for (let i = 0; i < frames; i += 1) {
223
+ if (HEAPU8[resets + i]) resetFrames.push(i + this.offset);
224
+ }
225
+ // Nullability follows what the caller asked for, never how many frames
226
+ // came back: a push too short to complete a frame returns empty arrays,
227
+ // matching kws_runtime, so callers can concatenate without special cases.
228
+ const read = (view, pointer, stride, length) => (
229
+ pointer || length === 0 ? view.slice(pointer / stride, pointer / stride + length) : null);
230
+ const result = {
231
+ frames: count,
232
+ frameOffset: this.offset,
233
+ resetFrames,
234
+ posteriors: want.posteriors
235
+ ? read(HEAP32, q31, 4, frames * this.model.nClasses) : null,
236
+ scores: want.scores && k ? read(HEAP16, scores, 2, frames * k) : null,
237
+ rawScores: want.rawScores && k ? read(HEAP16, raw, 2, frames * k) : null,
238
+ fires: want.events && k ? read(HEAPU8, fires, 1, frames * s * k) : null,
239
+ gates: want.gates && k ? read(HEAPU8, gates, 1, frames) : null,
240
+ metadata: {
241
+ frontendId: this.rt.frontendId,
242
+ model: this.model.identity,
243
+ lang: this.model.language,
244
+ nClasses: this.model.nClasses,
245
+ inputMode: cachedMel ? 'cached_mel' : 'pcm',
246
+ cpuKernel: this.rt.fn.cpu_kernel(),
247
+ finalization: 'complete_model_frames_no_eof_padding',
248
+ sensitivities: Array.from(this.sensitivities),
249
+ sensitivityLayout: this.perKeyword ? "per_keyword" : "grid",
250
+ keywordMode: this.mode === 0 ? 'independent' : 'production_arbitrated',
251
+ },
252
+ };
253
+ if (!cachedMel) this.pending = (this.pending + input.length) % 512;
254
+ this.offset += frames;
255
+ return result;
256
+ } finally {
257
+ scratch.free();
258
+ }
259
+ }
260
+
261
+ /** Drops the incomplete PCM tail; never appends synthetic EOF silence. */
262
+ finish() {
263
+ this.check();
264
+ const discarded = this.rt.fn.session_finish(this.pointer);
265
+ if (discarded < 0) throw fail(this.rt);
266
+ this.finished = true;
267
+ return { frames: this.offset, discardedSamples: discarded };
268
+ }
269
+
270
+ runPcm(pcm) {
271
+ if (this.offset || this.pending || this.finished) {
272
+ throw new Error('runPcm requires a fresh session; use pushPcm to continue');
273
+ }
274
+ const result = this.pushPcm(pcm);
275
+ Object.assign(result.metadata, this.finish());
276
+ return result;
277
+ }
278
+ }
279
+
280
+ export class Kws {
281
+ constructor(module) {
282
+ this.rt = { module, fn: bind(module) };
283
+ if (this.rt.fn.abi_version() !== 1) throw new Error('Unsupported kws native ABI');
284
+ this.rt.frontendId = (this.rt.fn.frontend_id() >>> 0).toString(16).padStart(8, '0');
285
+ }
286
+
287
+ get abiVersion() { return this.rt.fn.abi_version(); }
288
+
289
+ get frontendId() { return this.rt.frontendId; }
290
+
291
+ get cpuKernel() { return this.rt.fn.cpu_kernel(); }
292
+
293
+ /** Language preset: symbols, blank, class count, inventory identity. */
294
+ language(code = 'en') {
295
+ const scratch = new Scratch(this.rt);
296
+ try {
297
+ const json = this.rt.fn.language(scratch.string(code));
298
+ if (!json) throw fail(this.rt);
299
+ return JSON.parse(json);
300
+ } finally {
301
+ scratch.free();
302
+ }
303
+ }
304
+
305
+ /**
306
+ * Loads a model container from memory. The bytes pass through MEMFS so the
307
+ * container is parsed by exactly the path the native build validates,
308
+ * including its frontend-id mismatch diagnostics.
309
+ * @param {Uint8Array} bytes
310
+ */
311
+ loadModel(bytes, { lang = 'en' } = {}) {
312
+ const preset = this.language(lang);
313
+ const path = `/model-${Math.random().toString(36).slice(2)}.bin`;
314
+ this.rt.module.FS.writeFile(path, bytes);
315
+ const scratch = new Scratch(this.rt);
316
+ try {
317
+ const pointer = checked(this.rt, this.rt.fn.model_load(
318
+ scratch.string(path), scratch.string(lang),
319
+ ));
320
+ return new Model(this.rt, pointer, {
321
+ language: lang, nClasses: preset.n_classes, identity: null,
322
+ });
323
+ } finally {
324
+ scratch.free();
325
+ this.rt.module.FS.unlink(path);
326
+ }
327
+ }
328
+
329
+ /** @param {Int16Array} affine80 @param {Int8Array} values */
330
+ modelFromTensors(affine80, values, frontendId, { lang = 'en' } = {}) {
331
+ const preset = this.language(lang);
332
+ const scratch = new Scratch(this.rt);
333
+ try {
334
+ const pointer = checked(this.rt, this.rt.fn.model_tensors(
335
+ frontendId, scratch.typed(affine80), scratch.typed(values),
336
+ values.length, scratch.string(lang),
337
+ ));
338
+ return new Model(this.rt, pointer, {
339
+ language: lang, nClasses: preset.n_classes, identity: null,
340
+ });
341
+ } finally {
342
+ scratch.free();
343
+ }
344
+ }
345
+
346
+ frontend() { return new Frontend(this.rt); }
347
+
348
+ session(model, options) { return new Session(this.rt, model, options); }
349
+ }
350
+
351
+ /**
352
+ * Instantiates the engine.
353
+ *
354
+ * @param {object} options
355
+ * @param {boolean} [options.simd] load the -msimd128 build (build.sh --simd)
356
+ * @param {string} [options.kernel] KWS_CPU_KERNEL: 'portable' (default, as
357
+ * native), 'auto' or 'simd128'. Set through the emscripten environment so
358
+ * the C++ selects its kernel exactly as it does from a shell.
359
+ * @returns {Promise<Kws>}
360
+ */
361
+ export async function load({ simd = false, kernel = null, ...options } = {}) {
362
+ const { default: createKwsModule } = simd
363
+ ? await import('../dist/kws_engine.simd.mjs')
364
+ : await import('../dist/kws_engine.mjs');
365
+ const configured = kernel ?? (simd ? 'simd128' : null);
366
+ const module = await createKwsModule({
367
+ ...options,
368
+ preRun: [
369
+ (instance) => {
370
+ if (configured) instance.ENV.KWS_CPU_KERNEL = configured;
371
+ },
372
+ ...(options.preRun ?? []),
373
+ ],
374
+ });
375
+ return new Kws(module);
376
+ }
377
+
378
+ export default load;
wake/keywords.json ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": {
3
+ "id": "en-1",
4
+ "sha256": "8be3687d060f953d0069480cf53d1fd0aa66e04551c2a4b600823a992a864af8"
5
+ },
6
+ "keywords": [
7
+ {
8
+ "name": "hey phonlet",
9
+ "pronunciations": [
10
+ [16, 11, 18, 14, 1, 23, 21, 3, 31],
11
+ [16, 11, 14, 1, 23, 21, 3, 31]
12
+ ],
13
+ "threshold_loose": -1.28125,
14
+ "threshold_strict": -0.96484375,
15
+ "endpoint": false,
16
+ "metadata": {
17
+ "expected_error": {
18
+ "threshold_loose": 100.6,
19
+ "threshold_strict": 137.2,
20
+ "default": 118.2
21
+ },
22
+ "fa_factor_at_default": 5.76,
23
+ "flag": true
24
+ }
25
+ },
26
+ {
27
+ "name": "ok phonlet",
28
+ "pronunciations": [
29
+ [25, 20, 13, 14, 1, 23, 21, 3, 31]
30
+ ],
31
+ "threshold_loose": -1.4072265625,
32
+ "threshold_strict": -1.060546875,
33
+ "endpoint": false,
34
+ "metadata": {
35
+ "expected_error": {
36
+ "threshold_loose": 37.5,
37
+ "threshold_strict": 44.2,
38
+ "default": 38.2
39
+ },
40
+ "fa_factor_at_default": 1.64,
41
+ "flag": false
42
+ }
43
+ },
44
+ {
45
+ "name": "hey assistant",
46
+ "pronunciations": [
47
+ [16, 11, 18, 3, 29, 17, 29, 31, 3, 23, 31]
48
+ ],
49
+ "threshold_loose": -1.248046875,
50
+ "threshold_strict": -0.939453125,
51
+ "endpoint": false,
52
+ "metadata": {
53
+ "expected_error": {
54
+ "threshold_loose": 84.6,
55
+ "threshold_strict": 123.1,
56
+ "default": 98.4
57
+ },
58
+ "fa_factor_at_default": 4.35,
59
+ "flag": true
60
+ }
61
+ },
62
+ {
63
+ "name": "assistant",
64
+ "pronunciations": [
65
+ [3, 29, 17, 29, 31, 3, 23, 31]
66
+ ],
67
+ "threshold_loose": -0.869140625,
68
+ "threshold_strict": -0.451171875,
69
+ "endpoint": false,
70
+ "metadata": {
71
+ "expected_error": {
72
+ "threshold_loose": 48.2,
73
+ "threshold_strict": 69.6,
74
+ "default": 52.7
75
+ },
76
+ "fa_factor_at_default": 1.74,
77
+ "flag": false
78
+ }
79
+ },
80
+ {
81
+ "name": "hey wake",
82
+ "pronunciations": [
83
+ [16, 11, 18, 36, 13, 20]
84
+ ],
85
+ "threshold_loose": -1.4638671875,
86
+ "threshold_strict": -1.0087890625,
87
+ "endpoint": false,
88
+ "metadata": {
89
+ "expected_error": {
90
+ "threshold_loose": 121.8,
91
+ "threshold_strict": 178.1,
92
+ "default": 148.3
93
+ },
94
+ "fa_factor_at_default": 4.37,
95
+ "flag": true
96
+ }
97
+ }
98
+ ],
99
+ "metadata": {
100
+ "description": "The English phrases shipped with Phonlet Wake; pronunciations chosen by hand."
101
+ }
102
+ }
wake/model.pwake ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8be3687d060f953d0069480cf53d1fd0aa66e04551c2a4b600823a992a864af8
3
+ size 1013825
wake/package.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@phonlet-ai/wake-web",
3
+ "version": "0.1.0",
4
+ "description": "Phonlet Wake worker-based browser SDK",
5
+ "license": "PolyForm-Noncommercial-1.0.0",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./index.d.ts",
10
+ "import": "./index.mjs"
11
+ },
12
+ "./capture": {
13
+ "types": "./capture.d.ts",
14
+ "import": "./capture.mjs"
15
+ },
16
+ "./advanced": "./js/kws.mjs"
17
+ },
18
+ "files": [
19
+ "*.mjs",
20
+ "*.d.ts",
21
+ "js",
22
+ "dist",
23
+ "README.md",
24
+ "LICENSE",
25
+ "THIRD_PARTY_NOTICES.md"
26
+ ],
27
+ "scripts": {
28
+ "build": "bash ../../engine/wasm/build.sh && bash ../../engine/wasm/build.sh --simd",
29
+ "test": "node test/smoke.mjs && node test/smoke.mjs --simd"
30
+ },
31
+ "engines": {
32
+ "node": ">=18"
33
+ },
34
+ "private": true,
35
+ "types": "./index.d.ts"
36
+ }
wake/shared.mjs ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // One source for Node and Web validation. Generated package copies are self-contained.
2
+ export const SDK_VERSION = '0.1.0';
3
+ export const INVENTORY = '2017adc0505b3f530eef5b66a5b36019a434f04a4bd93a32b72f5070ee46baad';
4
+ export const FRONTEND = '3f047efa';
5
+ export class WakeError extends Error {
6
+ constructor(code, message) { super(message); this.name = 'WakeError'; this.code = code; }
7
+ }
8
+ export function fail(message, code = 'INVALID_ARGUMENT') { throw new WakeError(code, message); }
9
+ export function fields(value, required, optional = [], label = 'object') {
10
+ if (!value || typeof value !== 'object' || Array.isArray(value)) fail(`${label} must be an object`);
11
+ for (const key of required) if (!Object.hasOwn(value, key)) fail(`${label}: missing ${key}`);
12
+ for (const key of Object.keys(value)) if (![...required, ...optional].includes(key)) fail(`${label}: unknown ${key}`);
13
+ }
14
+ export function sensitivity(value) {
15
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) fail('sensitivity must be a finite number in [0,1]');
16
+ return value;
17
+ }
18
+ export function freeze(value) {
19
+ if (value && typeof value === 'object') { Object.values(value).forEach(freeze); Object.freeze(value); }
20
+ return value;
21
+ }
22
+ export async function digest(bytes) {
23
+ return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), b => b.toString(16).padStart(2, '0')).join('');
24
+ }
25
+ function sha(value, label) { if (typeof value !== 'string' || !/^[0-9a-f]{64}$/.test(value)) fail(`invalid ${label} SHA-256`); }
26
+ const isObject = value => value && typeof value === 'object' && !Array.isArray(value);
27
+ const PHRASE = ['name','pronunciations','threshold_loose','threshold_strict','endpoint'];
28
+ // A keyword file as the threshold generator writes it: {"model": {"id", "sha256"} (optional),
29
+ // "keywords": [phrase, ...], "metadata": {...} (optional, never read by the engine)}.
30
+ // A bare list of phrases is the same file without "model" and "metadata".
31
+ export function readKeywordFile(value) {
32
+ if (Array.isArray(value)) value = {keywords: value};
33
+ fields(value, ['keywords'], ['model','metadata'], 'keyword file');
34
+ if (!Array.isArray(value.keywords) || !value.keywords.length) fail('keywords must be a nonempty list of phrases');
35
+ if (Object.hasOwn(value, 'model')) {
36
+ fields(value.model, ['id','sha256'], [], 'keyword file model');
37
+ if (typeof value.model.id !== 'string' || !value.model.id.trim()) fail('keyword file model id must be a nonempty string');
38
+ sha(value.model.sha256, 'model');
39
+ }
40
+ if (Object.hasOwn(value, 'metadata') && !isObject(value.metadata)) fail('keyword file metadata must be an object');
41
+ return value;
42
+ }
43
+ // The phrase layout shared by keyword files and phrases written in code.
44
+ export function validatePhrases(phrases) {
45
+ if (!Array.isArray(phrases) || !phrases.length) fail('keywords must be a nonempty list of phrases');
46
+ const seen = new Set();
47
+ for (const kw of phrases) {
48
+ fields(kw, PHRASE, ['id','metadata','sensitivity'], 'phrase');
49
+ const id = Object.hasOwn(kw, 'id') ? kw.id : kw.name;
50
+ for (const [key, value] of [['name', kw.name], ['id', id]]) if (typeof value !== 'string' || !value.trim()) fail(`phrase ${key} must be a nonempty string`);
51
+ if (seen.has(id)) fail(`duplicate phrase: ${id}`); seen.add(id);
52
+ if (typeof kw.endpoint !== 'boolean') fail('phrase endpoint must be true or false');
53
+ if (Object.hasOwn(kw, 'metadata') && !isObject(kw.metadata)) fail('phrase metadata must be an object');
54
+ for (const key of ['threshold_loose','threshold_strict']) if (typeof kw[key] !== 'number' || !Number.isFinite(kw[key])) fail(`${key} must be finite`);
55
+ if (kw.threshold_loose > kw.threshold_strict) fail('threshold_loose must be <= threshold_strict');
56
+ if (!Array.isArray(kw.pronunciations) || !kw.pronunciations.length) fail('phrase needs at least one pronunciation');
57
+ for (const v of kw.pronunciations) if (!Array.isArray(v) || !v.length || v.length > 256 || v.some(p => !Number.isInteger(p) || p < 1 || p >= 40)) fail('invalid pronunciation phone IDs');
58
+ }
59
+ return phrases;
60
+ }
61
+ // Validated private copies of the phrases, each with its resolved sensitivity. A keyword file
62
+ // that names its model must name this one.
63
+ export function selectPhrases(value, modelSha256, defaultValue = 0.5) {
64
+ sensitivity(defaultValue);
65
+ const file = readKeywordFile(value);
66
+ if (file.model && file.model.sha256 !== modelSha256) fail(`these keywords were made for model ${file.model.id} (${file.model.sha256.slice(0,12)}), not this model (${modelSha256.slice(0,12)})`, 'INCOMPATIBLE_ARTIFACT');
67
+ const phrases = validatePhrases(JSON.parse(JSON.stringify(file.keywords)));
68
+ return freeze(phrases.map(kw => ({
69
+ id: Object.hasOwn(kw, 'id') ? kw.id : kw.name, ...Object.fromEntries(PHRASE.map(k => [k, kw[k]])),
70
+ metadata: kw.metadata ?? {}, sensitivity: Object.hasOwn(kw, 'sensitivity') ? sensitivity(kw.sensitivity) : defaultValue,
71
+ })));
72
+ }
73
+ export async function keywordsSha256(selected) {
74
+ return digest(new TextEncoder().encode(JSON.stringify(selected.map(({sensitivity: _, ...kw}) => kw))));
75
+ }
76
+ export function options(value, extra = []) {
77
+ fields(value, ['model','keywords'], ['sensitivity','keywordMode',...extra], 'Wake options');
78
+ const mode = Object.hasOwn(value, 'keywordMode') ? value.keywordMode : 'production_arbitrated';
79
+ if (!['independent','production_arbitrated'].includes(mode)) fail('invalid keywordMode');
80
+ const defaultValue = Object.hasOwn(value, 'sensitivity') ? sensitivity(value.sensitivity) : 0.5;
81
+ return {mode, defaultValue};
82
+ }
83
+ export function events(fires, offset, selected) {
84
+ const found = [], k = selected.length;
85
+ for (let i=0; i<fires.length; i++) if (fires[i]) {
86
+ const index = i % k, frame = offset + Math.floor(i/k), kw = selected[index];
87
+ found.push(Object.freeze({keywordId:kw.id,keyword:kw.name,keywordIndex:index,frameIndex:frame,
88
+ sampleIndex:(frame+1)*512,timeSeconds:(frame+1)*512/16000,sensitivity:kw.sensitivity}));
89
+ }
90
+ return found;
91
+ }
92
+ export function pcm(value) {
93
+ if (!(value instanceof Int16Array) || (typeof SharedArrayBuffer !== 'undefined' && value.buffer instanceof SharedArrayBuffer)) fail('expected an owned Int16Array of mono 16 kHz PCM');
94
+ return value;
95
+ }
96
+ export function readWav(bytes) {
97
+ if (!(bytes instanceof Uint8Array)) fail('WAV input must be bytes');
98
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
99
+ const tag = p => String.fromCharCode(...bytes.subarray(p,p+4));
100
+ if (bytes.length < 12 || tag(0) !== 'RIFF' || tag(8) !== 'WAVE' || view.getUint32(4,true)+8 !== bytes.length) fail('invalid or truncated RIFF WAV');
101
+ let format = false, data = null;
102
+ for (let p=12; p+8<=bytes.length;) {
103
+ const size = view.getUint32(p+4,true), start=p+8, end=start+size;
104
+ if (end>bytes.length) fail('truncated WAV chunk');
105
+ if (tag(p)==='fmt ') {
106
+ if (size<16 || view.getUint16(start,true)!==1 || view.getUint16(start+2,true)!==1 || view.getUint32(start+4,true)!==16000 || view.getUint16(start+12,true)!==2 || view.getUint16(start+14,true)!==16) fail('audio must be mono 16 kHz signed PCM16 WAV');
107
+ format=true;
108
+ } else if (tag(p)==='data') { if (data) fail('multiple WAV data chunks'); data=[start,size]; }
109
+ p=end+(size%2);
110
+ }
111
+ if (!format || !data || data[1]%2) fail('missing or invalid WAV format/data');
112
+ const output = new Int16Array(data[1]/2);
113
+ for (let i=0;i<output.length;i++) output[i]=view.getInt16(data[0]+i*2,true);
114
+ return output;
115
+ }
wake/worker.mjs ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {load} from './js/kws.mjs';
2
+ import {WakeError, validatePhrases, keywordsSha256, events, digest, freeze, INVENTORY, FRONTEND, SDK_VERSION} from './shared.mjs';
3
+ let engine,model,session,selected;
4
+ let work=Promise.resolve();
5
+ self.onmessage=({data})=>{
6
+ work=work.then(async()=>{
7
+ const {id,operation,args}=data;
8
+ try{
9
+ let result;
10
+ if(operation==='create'){
11
+ if(session)throw new WakeError('INVALID_STATE','already created');
12
+ selected=freeze(validatePhrases(args.keywords));
13
+ const wasmUrl=new URL(args.simd?'./dist/kws_engine.simd.wasm':'./dist/kws_engine.wasm',import.meta.url);
14
+ const response=await fetch(wasmUrl);if(!response.ok)throw new WakeError('CORRUPT_ARTIFACT','cannot load WASM engine');
15
+ const wasmBinary=new Uint8Array(await response.arrayBuffer());
16
+ const engineSha256=await digest(wasmBinary);
17
+ engine=await load({simd:args.simd,wasmBinary});
18
+ if(engine.abiVersion!==1||engine.frontendId!==FRONTEND||engine.language().inventory_id!==INVENTORY)throw new WakeError('INCOMPATIBLE_ARTIFACT','WASM engine identity mismatch');
19
+ const modelSha256=await digest(args.model);
20
+ model=engine.loadModel(args.model);
21
+ try{session=engine.session(model,{keywords:selected,keywordSensitivities:selected.map(k=>k.sensitivity),mode:args.mode,outputs:{events:true}});}
22
+ catch(error){model.close();throw error;}
23
+ result={sdkVersion:SDK_VERSION,engineAbi:1,engineSha256,keywordsSha256:await keywordsSha256(selected),keywordMode:args.mode,scorer:'production',scorerOptions:'',backend:args.simd?'wasm-simd':'wasm-scalar',frontendId:FRONTEND,inventoryId:INVENTORY,modelSha256};
24
+ }else if(operation==='process'){
25
+ if(!session)throw new WakeError('INVALID_STATE','worker not initialized');
26
+ const output=session.pushPcm(args);result=events(output.fires,output.frameOffset,selected);
27
+ }else if(operation==='finish'){
28
+ result=session.finish();
29
+ }else if(operation==='close'){
30
+ session?.close();model?.close();session=model=engine=null;result=null;
31
+ }else throw new WakeError('INVALID_ARGUMENT','unknown worker operation');
32
+ self.postMessage({id,result});
33
+ }catch(error){self.postMessage({id,error:{code:error.code??'ENGINE_FAILURE',message:error.message??String(error)}});}
34
+ });
35
+ };