@desert-ant-labs/clear 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,136 @@
1
+ # Desert Ant Labs Source-Available License
2
+
3
+ Version 1.0 · 2026-06-15
4
+
5
+ Copyright © 2026 Studio Company B.V., trading as Desert Ant Labs (`desertant.ai`).
6
+
7
+ This license governs Your use of the software, model weights, datasets, documentation, and associated assets in this repository (collectively, the **"Licensed Materials"**). It is a **source-available license intended for professional and business use**; it is not an OSI-approved open-source license. The rights granted here are subject to a per-Model usage cap and the other terms set out below.
8
+
9
+ ## Definitions
10
+
11
+ - **"Desert Ant Labs"** (also "We", "Us", "Our") — Studio Company B.V., a private limited liability company (*besloten vennootschap*) incorporated under the laws of the Netherlands, with statutory seat in Amsterdam, registered with the Dutch Chamber of Commerce (KvK) under number **81228112**, trading as Desert Ant Labs.
12
+ - **"Model"** — a set of trained weights published by Desert Ant Labs under a single HuggingFace repository (for example, `huggingface.co/desert-ant-labs/eye`). Each Model is a distinct work under this license.
13
+ - **"Monthly Active User"** or **"MAU"** — a unique end user who interacts with a feature powered by a Model during a calendar month. Internal use by Your own employees and contractors does not count.
14
+ - **"You"** — the individual or legal entity exercising rights under this license.
15
+
16
+ ## 0. Acceptance
17
+
18
+ By downloading, accessing, using, copying, modifying, or distributing the Licensed Materials, You agree to be bound by this license. If You do not agree, You may not use the Licensed Materials.
19
+
20
+ ## 1. Grant
21
+
22
+ Subject to Your continued compliance with this license, Desert Ant Labs grants You a worldwide, royalty-free, non-exclusive, non-transferable, non-sublicensable license to use, reproduce, modify, and distribute the Licensed Materials.
23
+
24
+ ## 2. Free-tier use
25
+
26
+ You may use the Licensed Materials free of charge, including for commercial purposes, subject to the following per-Model threshold:
27
+
28
+ > **For each Desert Ant Labs Model that Your products incorporate, the aggregate Monthly Active Users across all Your products must not exceed 100,000 in any calendar month.**
29
+
30
+ The threshold applies independently to each Model. Two Models at 50,000 MAU each do not combine into 100,000 MAU; each is independently within its own free-tier limit.
31
+
32
+ If a repository contains only software (no trained Model weights), no MAU threshold applies to that software on its own. The threshold attaches to the Models the software is used with.
33
+
34
+ ## 3. Research and academic use
35
+
36
+ Use of the Licensed Materials for non-commercial scientific research and academic publications is exempt from the MAU threshold in Section 2, provided that any resulting publication credits "Desert Ant Labs" and links to the relevant Model repository.
37
+
38
+ ## 4. Commercial license
39
+
40
+ If Your aggregate MAU for any Model exceeds 100,000 (or You expect it to within the next calendar month), You must obtain a commercial license from Desert Ant Labs before continuing to distribute or operate any product that incorporates that Model. A commercial license covers only the Models named in it; other Models remain under the free tier subject to their own thresholds.
41
+
42
+ Contact: <licensing@desertant.ai>.
43
+
44
+ ## 5. Patent grant
45
+
46
+ Each contributor to the Licensed Materials grants You a perpetual, worldwide, non-exclusive, royalty-free, irrevocable (except as stated in this Section) patent license to make, use, sell, offer to sell, and import the Licensed Materials, where such license applies only to those patent claims licensable by that contributor that are necessarily infringed by the Licensed Materials.
47
+
48
+ **If You institute patent litigation against any entity** (including a cross-claim or counterclaim in a lawsuit) alleging that the Licensed Materials infringe a patent, **all patent licenses granted to You under this license terminate as of the date such litigation is filed.**
49
+
50
+ ## 6. Restrictions
51
+
52
+ You may not:
53
+
54
+ 1. Sell, sublicense, or otherwise distribute the Licensed Materials themselves, or any substantially unmodified derivative of them, as a standalone product or hosted service.
55
+ 2. Use the Licensed Materials to train, distill, fine-tune, or otherwise derive a model that You release or distribute under any license more permissive than this license, including any OSI-approved open-source license. Internal research, personal fine-tuning, and use of derivative models that remain under this license are not restricted.
56
+ 3. Remove or alter the copyright, license, attribution, or third-party notices in the Licensed Materials.
57
+
58
+ You may freely embed the Licensed Materials in Your own product, subject to Section 2 and the rest of this license.
59
+
60
+ ## 7. Attribution
61
+
62
+ You must retain this LICENSE file and the copyright notice in all copies and substantial portions of the Licensed Materials. Where Your product surfaces acknowledgements, third-party notices, or "About" / "Credits" screens, please credit **"Desert Ant Labs (`desertant.ai`)"**.
63
+
64
+ ## 8. Modifications
65
+
66
+ You may modify the Licensed Materials. If You distribute modified Licensed Materials, You must:
67
+
68
+ (a) include a prominent notice stating that You have modified them, with the date of modification; and
69
+ (b) ensure that Your distributed modifications are licensed under this license.
70
+
71
+ This license governs the Licensed Materials and modifications to them. Applications and products that merely incorporate, link to, or call the Licensed Materials are Your own work; their structure, source, and license are not constrained by this license, subject only to Sections 2, 6, and 7.
72
+
73
+ ## 9. Reporting
74
+
75
+ To enable Desert Ant Labs to administer the free tier, You agree:
76
+
77
+ (a) to maintain reasonable records of Your aggregate MAU per Model; and
78
+ (b) upon written request from Desert Ant Labs, to provide a reasonable summary of those records sufficient to confirm compliance with Section 2. Such requests will be made no more than once per calendar year per licensee, except in the case of a reasonable, specific suspicion of breach.
79
+
80
+ You are encouraged — but not required — to notify Desert Ant Labs at <licensing@desertant.ai> when Your aggregate MAU for any Model first exceeds 80,000.
81
+
82
+ ## 10. Trademarks
83
+
84
+ This license does not grant You any right to use the trade names, trademarks, service marks, or product names of Desert Ant Labs, except for the limited attribution use specified in Section 7. All goodwill arising from such attribution use inures to the benefit of Desert Ant Labs.
85
+
86
+ ## 11. Third-party components
87
+
88
+ The Licensed Materials may include or derive from components licensed by third parties. Those components remain subject to their own licenses; nothing in this license overrides those terms. Notices for such components are provided in the model card or in a `THIRD_PARTY_NOTICES.md` file alongside the Licensed Materials.
89
+
90
+ ## 12. Termination
91
+
92
+ This license terminates automatically and immediately upon any of the following:
93
+
94
+ (a) Your aggregate MAU for any Model exceeds 100,000 and You do not obtain a commercial license within thirty (30) days;
95
+ (b) Your breach of Section 6 (Restrictions); or
96
+ (c) Your institution of patent litigation as described in Section 5.
97
+
98
+ For any other curable breach, Desert Ant Labs will provide written notice; if the breach is not cured within thirty (30) days of receipt of that notice, this license terminates as of the date the notice was sent.
99
+
100
+ Upon termination, You must cease using and distributing the Licensed Materials. Sections 7 (Attribution, with respect to copies already in the field), 10 (Trademarks), 11 (Third-Party Components), 13 (No Warranty), 14 (Limitation of Liability), and 15 (Governing Law) survive termination.
101
+
102
+ ## 13. No warranty
103
+
104
+ THE LICENSED MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. Desert Ant Labs makes no representation that the Licensed Materials are error-free, secure, or suitable for any particular use.
105
+
106
+ ## 14. Limitation of liability
107
+
108
+ IN NO EVENT SHALL DESERT ANT LABS BE LIABLE FOR ANY INDIRECT, INCIDENTAL, CONSEQUENTIAL, SPECIAL, OR EXEMPLARY DAMAGES (INCLUDING LOST PROFITS, LOSS OF DATA, OR BUSINESS INTERRUPTION) ARISING FROM OR IN CONNECTION WITH THE LICENSED MATERIALS, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
109
+
110
+ DESERT ANT LABS' TOTAL CUMULATIVE LIABILITY UNDER OR IN CONNECTION WITH THIS LICENSE SHALL NOT EXCEED THE GREATER OF (A) ONE HUNDRED EUROS (€100) OR (B) THE TOTAL FEES PAID BY YOU TO DESERT ANT LABS UNDER A SEPARATE COMMERCIAL LICENSE IN THE TWELVE (12) MONTHS PRECEDING THE CLAIM.
111
+
112
+ Nothing in this license limits or excludes liability to the extent such limitation or exclusion is not permitted by applicable mandatory law, including liability for willful misconduct (*opzet*) or gross negligence (*bewuste roekeloosheid*) and any mandatory provision of Dutch consumer-protection law.
113
+
114
+ ## 15. Governing law and jurisdiction
115
+
116
+ This license is governed by the laws of the Netherlands, without regard to its conflict-of-laws provisions. The competent courts of Amsterdam, the Netherlands, have exclusive jurisdiction over any dispute arising under or in connection with this license, subject to mandatory provisions of applicable consumer-protection law.
117
+
118
+ The United Nations Convention on Contracts for the International Sale of Goods (CISG, 1980) does not apply to this license.
119
+
120
+ ## 16. Miscellaneous
121
+
122
+ (a) **Severability.** If any provision of this license is held unenforceable by a court of competent jurisdiction, the remaining provisions remain in full force and effect, and the unenforceable provision shall be interpreted to give effect to its intent to the greatest extent permitted by law.
123
+
124
+ (b) **No waiver.** Failure or delay by Desert Ant Labs to enforce any right under this license is not a waiver of that right.
125
+
126
+ (c) **Assignment.** You may not assign this license without Desert Ant Labs' prior written consent. Desert Ant Labs may freely assign this license to a successor in interest. This license binds and benefits each party's successors and permitted assigns.
127
+
128
+ (d) **Entire agreement.** This license, together with any separate commercial license referenced in Section 4, is the entire agreement between You and Desert Ant Labs regarding the Licensed Materials and supersedes all prior agreements on the same subject matter.
129
+
130
+ (e) **Language.** The authoritative version of this license is in English. Any translation is for convenience only; in the event of any conflict, the English version controls.
131
+
132
+ ---
133
+
134
+ Commercial licensing inquiries: <licensing@desertant.ai>.
135
+
136
+ © 2026 Studio Company B.V., trading as Desert Ant Labs. Statutory seat: Amsterdam, the Netherlands. KvK: **81228112**.
package/README.md ADDED
@@ -0,0 +1,143 @@
1
+ # @desert-ant-labs/clear
2
+
3
+ On-device speech enhancement for **Node and the browser**. Takes noisy mono
4
+ audio (laptop mic, untreated room, traffic) and returns a podcast-ready 48 kHz
5
+ signal: denoised and dereverbed by a fine-tuned DeepFilterNet 3 model, then
6
+ loudness-normalized to platform spec (EBU R128 / BS.1770).
7
+
8
+ ```ts
9
+ import { load, decodeToMono, encodeWav } from "@desert-ant-labs/clear";
10
+
11
+ const clear = await load({ variant: "studio" }); // fetches + caches the model
12
+ const pcm = await decodeToMono(file); // browser: File/Blob → mono 48 kHz
13
+ const { audio } = await clear.enhance(pcm, { mastering: "applePodcasts" });
14
+ const wav = new Blob([encodeWav(audio, 48_000)], { type: "audio/wav" });
15
+ ```
16
+
17
+ ## Features
18
+
19
+ - Runs everywhere the same import resolves — **Node, browsers, bundlers, and
20
+ edge/worker runtimes** — the right build is selected automatically
21
+ - Denoise + dereverb + **loudness mastering** (Apple Podcasts, Spotify, YouTube,
22
+ Broadcast presets, or a custom LUFS/dBTP target) in one call
23
+ - Two variants: `studio` (default, cleaner) and `natural` (preserves room tone)
24
+ - WebGPU when available, threaded WASM otherwise (browser); CPU (Node)
25
+ - The model is fetched from the Hugging Face Hub at a **pinned revision**, then
26
+ cached — to the **filesystem** on Node and to **Cache Storage** in the browser
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ npm install @desert-ant-labs/clear
32
+ ```
33
+
34
+ The ONNX Runtime is a **peer dependency** — install the one for your platform:
35
+
36
+ ```bash
37
+ npm install onnxruntime-web # browser / workers
38
+ npm install onnxruntime-node # Node / server
39
+ ```
40
+
41
+ ## Importing
42
+
43
+ Pure ESM. The **same import works everywhere** — the right build is selected by
44
+ the package `exports` map:
45
+
46
+ ```ts
47
+ import { load } from "@desert-ant-labs/clear";
48
+ ```
49
+
50
+ In a no-bundler browser page, map the bare specifiers with an import map (see
51
+ [`Examples/ClearWeb`](./Examples/ClearWeb)).
52
+
53
+ ## Usage
54
+
55
+ ### Browser
56
+
57
+ ```ts
58
+ import { load, decodeToMono, encodeWav } from "@desert-ant-labs/clear";
59
+
60
+ const clear = await load({
61
+ variant: "studio",
62
+ onDownloadProgress: (loaded, total) => console.log(`${loaded}/${total}`),
63
+ });
64
+
65
+ const pcm = await decodeToMono(file); // any format the browser can decode
66
+ const result = await clear.enhance(pcm, {
67
+ mastering: "applePodcasts", // or "spotify" | "youtube" | "broadcast" | "bypass"
68
+ onProgress: (stage, frac) => console.log(stage, frac),
69
+ });
70
+
71
+ const url = URL.createObjectURL(
72
+ new Blob([encodeWav(result.audio, result.sampleRate)], { type: "audio/wav" }),
73
+ );
74
+ ```
75
+
76
+ > Threaded WASM and WebGPU require a **cross-origin-isolated** page
77
+ > (`Cross-Origin-Opener-Policy: same-origin` + `Cross-Origin-Embedder-Policy:
78
+ > require-corp`/`credentialless`). The example `serve.py` sets these.
79
+
80
+ ### Node
81
+
82
+ Node has no Web Audio, so input is a `Float32Array` of mono PCM at 48 kHz. Use
83
+ `decodeWav` for WAV buffers, or decode compressed formats upstream (e.g. ffmpeg).
84
+
85
+ ```ts
86
+ import { readFile, writeFile } from "node:fs/promises";
87
+ import { load, decodeWav, encodeWav } from "@desert-ant-labs/clear";
88
+
89
+ const clear = await load({ variant: "studio" });
90
+ const { samples } = decodeWav(await readFile("in.wav"));
91
+ const { audio, measuredLUFS } = await clear.enhance(samples, { mastering: "applePodcasts" });
92
+ await writeFile("out.wav", encodeWav(audio, 48_000));
93
+ console.log("integrated loudness:", measuredLUFS, "LUFS");
94
+ ```
95
+
96
+ ## API
97
+
98
+ ### `load(options?) => Promise<ClearModel>`
99
+
100
+ Resolves the model (local dir → cache → Hugging Face Hub) and builds an
101
+ inference session. Options:
102
+
103
+ | Option | Default | Notes |
104
+ |---|---|---|
105
+ | `variant` | `"studio"` | `"studio"` or `"natural"` |
106
+ | `useCache` | `true` | Cache to disk (Node) / Cache Storage (browser) |
107
+ | `allowRemote` | `true` | Set `false` to require a local/cached copy |
108
+ | `localModelPath` | — | Node: dir of pre-downloaded `clear-*.onnx` |
109
+ | `cacheDir` | `~/.cache/clear` | Node only |
110
+ | `token` | `$HF_TOKEN` | Node only, for gated repos |
111
+ | `forceWasm` / `numThreads` | — | Browser only |
112
+ | `onDownloadProgress` | — | `(loaded, total) => void` |
113
+
114
+ ### `ClearModel.enhance(pcm, options?) => Promise<EnhanceResult>`
115
+
116
+ `pcm` is mono `Float32Array` at 48 kHz. Returns `{ audio, durationSec,
117
+ sampleRate, measuredLUFS, measuredTruePeakDBFS }`. Options: `mastering`
118
+ (preset name, `{ integratedLUFS, truePeakDBTP?, maxLoudnessGainDB? }`, or
119
+ `"bypass"`) and `onProgress`.
120
+
121
+ ### Also exported
122
+
123
+ `decodeToMono` (browser), `decodeWav`/`encodeWav`, `measureLUFS`,
124
+ `applyLimiter`, `MASTERING_PRESETS`, `setOrt` (inject a preloaded runtime),
125
+ and the `@desert-ant-labs/clear/core` subpath for the platform-agnostic
126
+ `ClearModel`.
127
+
128
+ ## Example
129
+
130
+ [`Examples/ClearWeb`](./Examples/ClearWeb) is a no-bundler browser demo (file
131
+ pick → decode → enhance → before/after playback + WAV download):
132
+
133
+ ```bash
134
+ npm run build # build dist/ at the repo root
135
+ python3 Examples/ClearWeb/serve.py # serves the repo root with COOP/COEP
136
+ # open http://localhost:8765/Examples/ClearWeb/
137
+ ```
138
+
139
+ ## License
140
+
141
+ Source-available under the [Desert Ant Labs Source-Available License](./LICENSE.md).
142
+ The model is published at
143
+ [`huggingface.co/desert-ant-labs/clear`](https://huggingface.co/desert-ant-labs/clear).
@@ -0,0 +1,56 @@
1
+ # Third-party notices: clear-js
2
+
3
+ The `clear` models this package runs (`clear-studio`, `clear-natural`) are downloaded at runtime from `huggingface.co/desert-ant-labs/clear` and are a fine-tune of an upstream architecture. The upstream license applies to that base; nothing in the Desert Ant Labs Source-Available License overrides it.
4
+
5
+ For training-time dependencies and data sources see [`THIRD_PARTY_NOTICES.md` in clear-training](https://github.com/Desert-Ant-Labs/clear-training/blob/main/hf/THIRD_PARTY_NOTICES.md). This file covers only what's used at inference time.
6
+
7
+ ## Runtime model components
8
+
9
+ ### DeepFilterNet 3 (Hendrik Schröter)
10
+ - **Source:** [github.com/Rikorose/DeepFilterNet](https://github.com/Rikorose/DeepFilterNet) (DFN3-half configuration).
11
+ - **License:** MIT License.
12
+ - **Use:** Base architecture for both `clear-studio` and `clear-natural`. Fine-tuned on the Desert Ant Labs speech corpus and exported to ONNX. The shipped `.onnx` is bit-identical to the trained graph within fp16 precision.
13
+
14
+ ## Runtime library dependencies
15
+
16
+ These are **peer dependencies** — installed by the host application, not bundled in this package — but required for it to run.
17
+
18
+ ### ONNX Runtime (Microsoft)
19
+ - **Packages:** `onnxruntime-web` (browser/workers), `onnxruntime-node` (Node).
20
+ - **Source:** [github.com/microsoft/onnxruntime](https://github.com/microsoft/onnxruntime).
21
+ - **License:** MIT License.
22
+ - **Use:** Executes the ONNX model graph.
23
+
24
+ The STFT/ISTFT, ERB filterbank, feature extraction, WAV codec, and R128 loudness mastering are original Desert Ant Labs implementations with no third-party code.
25
+
26
+ ## License-notice retention
27
+
28
+ The MIT license requires preservation of the upstream copyright and permission notice in substantial portions of the software.
29
+
30
+ ### DeepFilterNet 3
31
+
32
+ ```
33
+ MIT License
34
+
35
+ Copyright (c) 2022 Hendrik Schröter
36
+
37
+ Permission is hereby granted, free of charge, to any person obtaining a copy
38
+ of this software and associated documentation files (the "Software"), to deal
39
+ in the Software without restriction, including without limitation the rights
40
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
41
+ copies of the Software, and to permit persons to whom the Software is
42
+ furnished to do so, subject to the following conditions:
43
+
44
+ The above copyright notice and this permission notice shall be included in all
45
+ copies or substantial portions of the Software.
46
+
47
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
48
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
49
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
50
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
51
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
52
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
53
+ SOFTWARE.
54
+ ```
55
+
56
+ The DeepFilterNet 3 notice also ships inside `huggingface.co/desert-ant-labs/clear` alongside the model weights. ONNX Runtime ships its own MIT license text within its npm package.
@@ -0,0 +1,5 @@
1
+ import type { FileCache } from "./hub.js";
2
+ /** Filesystem-backed cache (Node): downloaded model files persist across runs. */
3
+ export declare function fsCache(cacheDir: string): FileCache;
4
+ /** Reads model files from a local directory (for `localModelPath`). */
5
+ export declare function localReader(dir: string): (name: string) => Promise<Uint8Array | null>;
@@ -0,0 +1,32 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ const keyToPath = (cacheDir, key) => join(cacheDir, key.replace(/^https?:\/\//, "").replace(/[^a-zA-Z0-9._/-]/g, "_"));
4
+ /** Filesystem-backed cache (Node): downloaded model files persist across runs. */
5
+ export function fsCache(cacheDir) {
6
+ return {
7
+ async get(key) {
8
+ try {
9
+ return new Uint8Array(await readFile(keyToPath(cacheDir, key)));
10
+ }
11
+ catch {
12
+ return null;
13
+ }
14
+ },
15
+ async put(key, data) {
16
+ const path = keyToPath(cacheDir, key);
17
+ await mkdir(dirname(path), { recursive: true });
18
+ await writeFile(path, data);
19
+ },
20
+ };
21
+ }
22
+ /** Reads model files from a local directory (for `localModelPath`). */
23
+ export function localReader(dir) {
24
+ return async (name) => {
25
+ try {
26
+ return new Uint8Array(await readFile(join(dir, name)));
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ };
32
+ }
@@ -0,0 +1,3 @@
1
+ import type { FileCache } from "./hub.js";
2
+ /** Cache Storage-backed cache (browser): downloaded model files persist across visits. */
3
+ export declare function webCache(name?: string): FileCache;
@@ -0,0 +1,24 @@
1
+ /** Cache Storage-backed cache (browser): downloaded model files persist across visits. */
2
+ export function webCache(name = "clear-model") {
3
+ return {
4
+ async get(key) {
5
+ try {
6
+ const cache = await caches.open(name);
7
+ const res = await cache.match(key);
8
+ return res ? new Uint8Array(await res.arrayBuffer()) : null;
9
+ }
10
+ catch {
11
+ return null;
12
+ }
13
+ },
14
+ async put(key, data) {
15
+ try {
16
+ const cache = await caches.open(name);
17
+ await cache.put(key, new Response(data));
18
+ }
19
+ catch {
20
+ /* caching is best-effort */
21
+ }
22
+ },
23
+ };
24
+ }
@@ -0,0 +1,2 @@
1
+ /** Decode a `File`/`Blob`/`ArrayBuffer` to mono PCM at `sampleRate` (default 48 kHz). */
2
+ export declare function decodeToMono(input: Blob | ArrayBuffer, sampleRate?: number): Promise<Float32Array>;
@@ -0,0 +1,49 @@
1
+ //
2
+ // Decode any browser-supported audio file to mono Float32 at 48 kHz, using
3
+ // an OfflineAudioContext for resampling so the math is the browser's native
4
+ // path, not a linear interpolation.
5
+ import { SR } from "./model.js";
6
+ /** Decode a `File`/`Blob`/`ArrayBuffer` to mono PCM at `sampleRate` (default 48 kHz). */
7
+ export async function decodeToMono(input, sampleRate = SR) {
8
+ const buf = input instanceof ArrayBuffer ? input : await input.arrayBuffer();
9
+ const Ctor = (typeof AudioContext !== "undefined" && AudioContext) || window?.AudioContext || window?.webkitAudioContext;
10
+ if (!Ctor)
11
+ throw new Error("clear: Web Audio API unavailable (use the Node entry, or decode to a Float32Array first)");
12
+ const tmpCtx = new Ctor();
13
+ let decoded;
14
+ try {
15
+ decoded = await tmpCtx.decodeAudioData(buf.slice(0));
16
+ }
17
+ finally {
18
+ await tmpCtx.close();
19
+ }
20
+ const mono = mixToMono(decoded);
21
+ if (decoded.sampleRate === sampleRate)
22
+ return mono;
23
+ return resampleOffline(mono, decoded.sampleRate, sampleRate);
24
+ }
25
+ function mixToMono(audioBuffer) {
26
+ const n = audioBuffer.length;
27
+ const c = audioBuffer.numberOfChannels;
28
+ if (c === 1)
29
+ return audioBuffer.getChannelData(0).slice();
30
+ const out = new Float32Array(n);
31
+ for (let ch = 0; ch < c; ch++) {
32
+ const data = audioBuffer.getChannelData(ch);
33
+ for (let i = 0; i < n; i++)
34
+ out[i] += data[i] / c;
35
+ }
36
+ return out;
37
+ }
38
+ async function resampleOffline(mono, srIn, srOut) {
39
+ const outLen = Math.ceil((mono.length * srOut) / srIn);
40
+ const ctx = new OfflineAudioContext(1, outLen, srOut);
41
+ const src = ctx.createBuffer(1, mono.length, srIn);
42
+ src.copyToChannel(mono, 0);
43
+ const node = ctx.createBufferSource();
44
+ node.buffer = src;
45
+ node.connect(ctx.destination);
46
+ node.start(0);
47
+ const rendered = await ctx.startRendering();
48
+ return rendered.getChannelData(0).slice();
49
+ }
package/dist/erb.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ export declare const ERB_WIDTHS: Int32Array;
2
+ export declare const N_ERB: number;
3
+ export declare const N_FREQ_FROM_ERB: number;
4
+ /**
5
+ * Mean per-bin power per band.
6
+ * @param power [nFrames, N_FREQ_FROM_ERB] row-major
7
+ * @returns [nFrames, N_ERB] row-major
8
+ */
9
+ export declare function projectPower(power: Float32Array, nFrames: number): Float32Array;
package/dist/erb.js ADDED
@@ -0,0 +1,40 @@
1
+ //
2
+ // ERB filterbank — band widths are fixed at training time. The trained
3
+ // model only accepts these widths.
4
+ export const ERB_WIDTHS = Int32Array.of(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 7, 7, 8, 10, 12, 13, 15, 18, 20, 24, 28, 31, 37, 42, 50, 56, 67);
5
+ export const N_ERB = ERB_WIDTHS.length;
6
+ export const N_FREQ_FROM_ERB = (() => {
7
+ let s = 0;
8
+ for (const w of ERB_WIDTHS)
9
+ s += w;
10
+ return s;
11
+ })();
12
+ const WIDTH_RECIP = new Float32Array(N_ERB);
13
+ for (let i = 0; i < N_ERB; i++)
14
+ WIDTH_RECIP[i] = 1.0 / ERB_WIDTHS[i];
15
+ /**
16
+ * Mean per-bin power per band.
17
+ * @param power [nFrames, N_FREQ_FROM_ERB] row-major
18
+ * @returns [nFrames, N_ERB] row-major
19
+ */
20
+ export function projectPower(power, nFrames) {
21
+ if (nFrames <= 0 || power.length !== nFrames * N_FREQ_FROM_ERB) {
22
+ return new Float32Array(0);
23
+ }
24
+ const out = new Float32Array(nFrames * N_ERB);
25
+ for (let t = 0; t < nFrames; t++) {
26
+ const rowIn = t * N_FREQ_FROM_ERB;
27
+ const rowOut = t * N_ERB;
28
+ let off = 0;
29
+ for (let band = 0; band < N_ERB; band++) {
30
+ const w = ERB_WIDTHS[band];
31
+ let sum = 0;
32
+ const p0 = rowIn + off;
33
+ for (let k = 0; k < w; k++)
34
+ sum += power[p0 + k];
35
+ out[rowOut + band] = sum * WIDTH_RECIP[band];
36
+ off += w;
37
+ }
38
+ }
39
+ return out;
40
+ }
@@ -0,0 +1,15 @@
1
+ export declare const N_DF = 96;
2
+ export declare const NORM_ALPHA = 0.99;
3
+ export interface Features {
4
+ /** [nFrames, N_ERB] row-major. */
5
+ featErb: Float32Array;
6
+ /** [nFrames, N_DF] row-major. */
7
+ featSpecReal: Float32Array;
8
+ /** [nFrames, N_DF] row-major. */
9
+ featSpecImag: Float32Array;
10
+ }
11
+ /**
12
+ * @param real [nFrames, nFreq] row-major
13
+ * @param imag [nFrames, nFreq] row-major
14
+ */
15
+ export declare function computeFeatures(real: Float32Array, imag: Float32Array, nFrames: number, nFreq: number): Features;
@@ -0,0 +1,59 @@
1
+ //
2
+ // Per-frame feature extraction (erb dB-norm + complex spec unit-norm).
3
+ // The model is highly scale-sensitive — keep this byte-exact with the
4
+ // Swift / Android references.
5
+ import { projectPower, N_ERB } from "./erb.js";
6
+ export const N_DF = 96;
7
+ export const NORM_ALPHA = 0.99;
8
+ /**
9
+ * @param real [nFrames, nFreq] row-major
10
+ * @param imag [nFrames, nFreq] row-major
11
+ */
12
+ export function computeFeatures(real, imag, nFrames, nFreq) {
13
+ const alpha = NORM_ALPHA;
14
+ const oneMinus = 1.0 - alpha;
15
+ const nDf = N_DF;
16
+ const nErb = N_ERB;
17
+ const power = new Float32Array(nFrames * nFreq);
18
+ for (let i = 0; i < power.length; i++) {
19
+ power[i] = real[i] * real[i] + imag[i] * imag[i];
20
+ }
21
+ const erbPower = projectPower(power, nFrames);
22
+ const erbDB = new Float32Array(erbPower.length);
23
+ const EPS = 1e-10;
24
+ for (let i = 0; i < erbDB.length; i++) {
25
+ erbDB[i] = 10 * Math.log10(erbPower[i] + EPS);
26
+ }
27
+ const featErb = new Float32Array(nFrames * nErb);
28
+ const erbState = new Float32Array(nErb);
29
+ const mnStep = (-90.0 - -60.0) / (nErb - 1);
30
+ for (let f = 0; f < nErb; f++)
31
+ erbState[f] = -60.0 + f * mnStep;
32
+ for (let t = 0; t < nFrames; t++) {
33
+ const off = t * nErb;
34
+ for (let f = 0; f < nErb; f++) {
35
+ erbState[f] = erbDB[off + f] * oneMinus + erbState[f] * alpha;
36
+ featErb[off + f] = (erbDB[off + f] - erbState[f]) / 40.0;
37
+ }
38
+ }
39
+ const featSpecReal = new Float32Array(nFrames * nDf);
40
+ const featSpecImag = new Float32Array(nFrames * nDf);
41
+ const s = new Float32Array(nDf);
42
+ const unStep = (0.0001 - 0.001) / (nDf - 1);
43
+ for (let f = 0; f < nDf; f++)
44
+ s[f] = 0.001 + f * unStep;
45
+ for (let t = 0; t < nFrames; t++) {
46
+ const inOff = t * nFreq;
47
+ const outOff = t * nDf;
48
+ for (let f = 0; f < nDf; f++) {
49
+ const rr = real[inOff + f];
50
+ const ii = imag[inOff + f];
51
+ const mag = Math.sqrt(rr * rr + ii * ii);
52
+ s[f] = mag * oneMinus + s[f] * alpha;
53
+ const inv = 1.0 / Math.sqrt(s[f]);
54
+ featSpecReal[outOff + f] = rr * inv;
55
+ featSpecImag[outOff + f] = ii * inv;
56
+ }
57
+ }
58
+ return { featErb, featSpecReal, featSpecImag };
59
+ }
package/dist/fft.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ /** Bluestein planner for a fixed length N. Reuse across many frames. */
2
+ export declare class BluesteinFFT {
3
+ readonly N: number;
4
+ readonly M: number;
5
+ private readonly aRe;
6
+ private readonly aIm;
7
+ private readonly Bf_Re;
8
+ private readonly Bf_Im;
9
+ private readonly Bi_Re;
10
+ private readonly Bi_Im;
11
+ private readonly _sRe;
12
+ private readonly _sIm;
13
+ constructor(N: number);
14
+ /**
15
+ * Out-of-place DFT of length N. `outRe`/`outIm` must each have length ≥ N.
16
+ * `inverse` selects forward (false) or inverse (true); neither applies 1/N.
17
+ */
18
+ transform(xRe: Float64Array, xIm: Float64Array, outRe: Float64Array, outIm: Float64Array, inverse?: boolean): void;
19
+ }