@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 +136 -0
- package/README.md +143 -0
- package/THIRD_PARTY_NOTICES.md +56 -0
- package/dist/cache-node.d.ts +5 -0
- package/dist/cache-node.js +32 -0
- package/dist/cache-web.d.ts +3 -0
- package/dist/cache-web.js +24 -0
- package/dist/decode-web.d.ts +2 -0
- package/dist/decode-web.js +49 -0
- package/dist/erb.d.ts +9 -0
- package/dist/erb.js +40 -0
- package/dist/features.d.ts +15 -0
- package/dist/features.js +59 -0
- package/dist/fft.d.ts +19 -0
- package/dist/fft.js +145 -0
- package/dist/hub.d.ts +34 -0
- package/dist/hub.js +74 -0
- package/dist/index.browser.d.ts +31 -0
- package/dist/index.browser.js +71 -0
- package/dist/index.node.d.ts +24 -0
- package/dist/index.node.js +44 -0
- package/dist/model.d.ts +50 -0
- package/dist/model.js +194 -0
- package/dist/ort.d.ts +34 -0
- package/dist/ort.js +38 -0
- package/dist/r128.d.ts +31 -0
- package/dist/r128.js +140 -0
- package/dist/stft.d.ts +26 -0
- package/dist/stft.js +105 -0
- package/dist/wav.d.ts +17 -0
- package/dist/wav.js +126 -0
- package/package.json +95 -0
package/dist/fft.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Bluestein FFT wrapping a radix-2 Cooley-Tukey kernel — needed because
|
|
3
|
+
// the clear STFT length N=960 isn't a power of two. Unnormalized DFT both
|
|
4
|
+
// directions (no 1/N); the STFT layer's `wnorm` compensates.
|
|
5
|
+
/** Bluestein planner for a fixed length N. Reuse across many frames. */
|
|
6
|
+
export class BluesteinFFT {
|
|
7
|
+
N;
|
|
8
|
+
M;
|
|
9
|
+
aRe;
|
|
10
|
+
aIm;
|
|
11
|
+
Bf_Re;
|
|
12
|
+
Bf_Im;
|
|
13
|
+
Bi_Re;
|
|
14
|
+
Bi_Im;
|
|
15
|
+
_sRe;
|
|
16
|
+
_sIm;
|
|
17
|
+
constructor(N) {
|
|
18
|
+
this.N = N;
|
|
19
|
+
let M = 1;
|
|
20
|
+
while (M < 2 * N - 1)
|
|
21
|
+
M <<= 1;
|
|
22
|
+
this.M = M;
|
|
23
|
+
const aRe = new Float64Array(N);
|
|
24
|
+
const aIm = new Float64Array(N);
|
|
25
|
+
for (let n = 0; n < N; n++) {
|
|
26
|
+
const ang = (-Math.PI * ((n * n) % (2 * N))) / N;
|
|
27
|
+
aRe[n] = Math.cos(ang);
|
|
28
|
+
aIm[n] = Math.sin(ang);
|
|
29
|
+
}
|
|
30
|
+
this.aRe = aRe;
|
|
31
|
+
this.aIm = aIm;
|
|
32
|
+
const bfRe = new Float64Array(M);
|
|
33
|
+
const bfIm = new Float64Array(M);
|
|
34
|
+
bfRe[0] = aRe[0];
|
|
35
|
+
bfIm[0] = -aIm[0];
|
|
36
|
+
for (let m = 1; m < N; m++) {
|
|
37
|
+
bfRe[m] = aRe[m];
|
|
38
|
+
bfIm[m] = -aIm[m];
|
|
39
|
+
bfRe[M - m] = aRe[m];
|
|
40
|
+
bfIm[M - m] = -aIm[m];
|
|
41
|
+
}
|
|
42
|
+
this.Bf_Re = bfRe;
|
|
43
|
+
this.Bf_Im = bfIm;
|
|
44
|
+
fftRadix2Inplace(this.Bf_Re, this.Bf_Im, M, false);
|
|
45
|
+
const biRe = new Float64Array(M);
|
|
46
|
+
const biIm = new Float64Array(M);
|
|
47
|
+
biRe[0] = aRe[0];
|
|
48
|
+
biIm[0] = aIm[0];
|
|
49
|
+
for (let m = 1; m < N; m++) {
|
|
50
|
+
biRe[m] = aRe[m];
|
|
51
|
+
biIm[m] = aIm[m];
|
|
52
|
+
biRe[M - m] = aRe[m];
|
|
53
|
+
biIm[M - m] = aIm[m];
|
|
54
|
+
}
|
|
55
|
+
this.Bi_Re = biRe;
|
|
56
|
+
this.Bi_Im = biIm;
|
|
57
|
+
fftRadix2Inplace(this.Bi_Re, this.Bi_Im, M, false);
|
|
58
|
+
this._sRe = new Float64Array(M);
|
|
59
|
+
this._sIm = new Float64Array(M);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Out-of-place DFT of length N. `outRe`/`outIm` must each have length ≥ N.
|
|
63
|
+
* `inverse` selects forward (false) or inverse (true); neither applies 1/N.
|
|
64
|
+
*/
|
|
65
|
+
transform(xRe, xIm, outRe, outIm, inverse = false) {
|
|
66
|
+
const { N, M, aRe, aIm, _sRe: sRe, _sIm: sIm } = this;
|
|
67
|
+
const BRe = inverse ? this.Bi_Re : this.Bf_Re;
|
|
68
|
+
const BIm = inverse ? this.Bi_Im : this.Bf_Im;
|
|
69
|
+
const cSign = inverse ? -1 : +1;
|
|
70
|
+
sRe.fill(0);
|
|
71
|
+
sIm.fill(0);
|
|
72
|
+
for (let n = 0; n < N; n++) {
|
|
73
|
+
const cr = aRe[n];
|
|
74
|
+
const ci = cSign * aIm[n];
|
|
75
|
+
const xr = xRe[n];
|
|
76
|
+
const xi = xIm[n];
|
|
77
|
+
sRe[n] = xr * cr - xi * ci;
|
|
78
|
+
sIm[n] = xr * ci + xi * cr;
|
|
79
|
+
}
|
|
80
|
+
fftRadix2Inplace(sRe, sIm, M, false);
|
|
81
|
+
for (let i = 0; i < M; i++) {
|
|
82
|
+
const sr = sRe[i];
|
|
83
|
+
const si = sIm[i];
|
|
84
|
+
const br = BRe[i];
|
|
85
|
+
const bi = BIm[i];
|
|
86
|
+
sRe[i] = sr * br - si * bi;
|
|
87
|
+
sIm[i] = sr * bi + si * br;
|
|
88
|
+
}
|
|
89
|
+
fftRadix2Inplace(sRe, sIm, M, true);
|
|
90
|
+
for (let k = 0; k < N; k++) {
|
|
91
|
+
const cr = aRe[k];
|
|
92
|
+
const ci = cSign * aIm[k];
|
|
93
|
+
const yr = sRe[k];
|
|
94
|
+
const yi = sIm[k];
|
|
95
|
+
outRe[k] = yr * cr - yi * ci;
|
|
96
|
+
outIm[k] = yr * ci + yi * cr;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function fftRadix2Inplace(re, im, M, inverse) {
|
|
101
|
+
for (let i = 1, j = 0; i < M; i++) {
|
|
102
|
+
let bit = M >> 1;
|
|
103
|
+
for (; j & bit; bit >>= 1)
|
|
104
|
+
j ^= bit;
|
|
105
|
+
j ^= bit;
|
|
106
|
+
if (i < j) {
|
|
107
|
+
let t = re[i];
|
|
108
|
+
re[i] = re[j];
|
|
109
|
+
re[j] = t;
|
|
110
|
+
t = im[i];
|
|
111
|
+
im[i] = im[j];
|
|
112
|
+
im[j] = t;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
for (let len = 2; len <= M; len <<= 1) {
|
|
116
|
+
const half = len >> 1;
|
|
117
|
+
const ang = ((inverse ? 2 : -2) * Math.PI) / len;
|
|
118
|
+
const wReStep = Math.cos(ang);
|
|
119
|
+
const wImStep = Math.sin(ang);
|
|
120
|
+
for (let i = 0; i < M; i += len) {
|
|
121
|
+
let wr = 1;
|
|
122
|
+
let wi = 0;
|
|
123
|
+
for (let j = 0; j < half; j++) {
|
|
124
|
+
const ur = re[i + j];
|
|
125
|
+
const ui = im[i + j];
|
|
126
|
+
const vr = re[i + j + half] * wr - im[i + j + half] * wi;
|
|
127
|
+
const vi = re[i + j + half] * wi + im[i + j + half] * wr;
|
|
128
|
+
re[i + j] = ur + vr;
|
|
129
|
+
im[i + j] = ui + vi;
|
|
130
|
+
re[i + j + half] = ur - vr;
|
|
131
|
+
im[i + j + half] = ui - vi;
|
|
132
|
+
const nwr = wr * wReStep - wi * wImStep;
|
|
133
|
+
wi = wr * wImStep + wi * wReStep;
|
|
134
|
+
wr = nwr;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (inverse) {
|
|
139
|
+
const s = 1 / M;
|
|
140
|
+
for (let i = 0; i < M; i++) {
|
|
141
|
+
re[i] *= s;
|
|
142
|
+
im[i] *= s;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
package/dist/hub.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Variant } from "./model.js";
|
|
2
|
+
export declare const DEFAULT_HOST = "https://huggingface.co";
|
|
3
|
+
export declare const DEFAULT_REPO = "desert-ant-labs/clear";
|
|
4
|
+
/** Pinned revision of the model repo (a commit SHA). */
|
|
5
|
+
export declare const DEFAULT_REVISION = "c02ff68ed0aa4e8fc4df4725a0ea83bf5b70b82f";
|
|
6
|
+
/** ONNX file name per variant in the model repo. */
|
|
7
|
+
export declare const MODEL_FILES: Record<Variant, string>;
|
|
8
|
+
/** Resolution + caching configuration (mutate the exported `env` to change defaults). */
|
|
9
|
+
export interface ClearEnv {
|
|
10
|
+
/** Hugging Face host serving the model repo. */
|
|
11
|
+
host: string;
|
|
12
|
+
/** Model repo id, e.g. `"desert-ant-labs/clear"`. */
|
|
13
|
+
repo: string;
|
|
14
|
+
/** Pinned revision (commit SHA, tag, or branch). */
|
|
15
|
+
revision: string;
|
|
16
|
+
/** Allow fetching from the Hugging Face Hub. Set `false` to require a local copy. */
|
|
17
|
+
allowRemote: boolean;
|
|
18
|
+
/** Cache downloaded files (filesystem on Node, Cache Storage in the browser). */
|
|
19
|
+
useCache: boolean;
|
|
20
|
+
/** Directory of pre-downloaded model files to use instead of the Hub (Node). */
|
|
21
|
+
localModelPath?: string;
|
|
22
|
+
/** Filesystem cache directory (Node). */
|
|
23
|
+
cacheDir?: string;
|
|
24
|
+
/** Optional Hugging Face access token (Node, for private/gated repos). */
|
|
25
|
+
token?: string;
|
|
26
|
+
}
|
|
27
|
+
/** A key/value store for cached file bytes, keyed by resolve URL. */
|
|
28
|
+
export interface FileCache {
|
|
29
|
+
get(key: string): Promise<Uint8Array | null>;
|
|
30
|
+
put(key: string, data: Uint8Array): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
export type DownloadProgress = (loaded: number, total: number) => void;
|
|
33
|
+
/** Resolves the ONNX bytes for `variant`: local dir → cache → Hugging Face Hub. */
|
|
34
|
+
export declare function loadModelBytes(env: ClearEnv, variant: Variant, cache: FileCache | null, readLocal?: (name: string) => Promise<Uint8Array | null>, onProgress?: DownloadProgress): Promise<Uint8Array>;
|
package/dist/hub.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Model resolution + caching, mirroring the emo/shapes hub: a model file is
|
|
3
|
+
// resolved from a local dir → cache → the Hugging Face Hub, at a pinned
|
|
4
|
+
// revision.
|
|
5
|
+
export const DEFAULT_HOST = "https://huggingface.co";
|
|
6
|
+
export const DEFAULT_REPO = "desert-ant-labs/clear";
|
|
7
|
+
/** Pinned revision of the model repo (a commit SHA). */
|
|
8
|
+
export const DEFAULT_REVISION = "c02ff68ed0aa4e8fc4df4725a0ea83bf5b70b82f";
|
|
9
|
+
/** ONNX file name per variant in the model repo. */
|
|
10
|
+
export const MODEL_FILES = {
|
|
11
|
+
studio: "clear-studio.onnx",
|
|
12
|
+
natural: "clear-natural.onnx",
|
|
13
|
+
};
|
|
14
|
+
function resolveUrl(env, name) {
|
|
15
|
+
return `${env.host}/${env.repo}/resolve/${env.revision}/${name}`;
|
|
16
|
+
}
|
|
17
|
+
async function fetchWithProgress(url, headers, onProgress) {
|
|
18
|
+
const res = await fetch(url, headers ? { headers } : undefined);
|
|
19
|
+
if (!res.ok)
|
|
20
|
+
throw new Error(`clear: failed to fetch ${url} (${res.status} ${res.statusText})`);
|
|
21
|
+
const total = Number(res.headers.get("content-length") ?? 0);
|
|
22
|
+
if (!res.body || !onProgress) {
|
|
23
|
+
return new Uint8Array(await res.arrayBuffer());
|
|
24
|
+
}
|
|
25
|
+
const reader = res.body.getReader();
|
|
26
|
+
const chunks = [];
|
|
27
|
+
let loaded = 0;
|
|
28
|
+
for (;;) {
|
|
29
|
+
const { done, value } = await reader.read();
|
|
30
|
+
if (done)
|
|
31
|
+
break;
|
|
32
|
+
chunks.push(value);
|
|
33
|
+
loaded += value.length;
|
|
34
|
+
onProgress(loaded, total);
|
|
35
|
+
}
|
|
36
|
+
const out = new Uint8Array(loaded);
|
|
37
|
+
let off = 0;
|
|
38
|
+
for (const c of chunks) {
|
|
39
|
+
out.set(c, off);
|
|
40
|
+
off += c.length;
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
/** Resolves the ONNX bytes for `variant`: local dir → cache → Hugging Face Hub. */
|
|
45
|
+
export async function loadModelBytes(env, variant, cache, readLocal, onProgress) {
|
|
46
|
+
const name = MODEL_FILES[variant];
|
|
47
|
+
if (!name)
|
|
48
|
+
throw new Error(`clear: unknown variant "${variant}"`);
|
|
49
|
+
if (readLocal) {
|
|
50
|
+
const local = await readLocal(name);
|
|
51
|
+
if (local)
|
|
52
|
+
return local;
|
|
53
|
+
}
|
|
54
|
+
const url = resolveUrl(env, name);
|
|
55
|
+
if (cache && env.useCache) {
|
|
56
|
+
const hit = await cache.get(url);
|
|
57
|
+
if (hit)
|
|
58
|
+
return hit;
|
|
59
|
+
}
|
|
60
|
+
if (!env.allowRemote) {
|
|
61
|
+
throw new Error(`clear: ${name} unavailable locally and remote loading is disabled`);
|
|
62
|
+
}
|
|
63
|
+
const headers = env.token ? { Authorization: `Bearer ${env.token}` } : undefined;
|
|
64
|
+
const data = await fetchWithProgress(url, headers, onProgress);
|
|
65
|
+
if (cache && env.useCache) {
|
|
66
|
+
try {
|
|
67
|
+
await cache.put(url, data);
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
/* caching is best-effort */
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return data;
|
|
74
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type ClearEnv, type DownloadProgress } from "./hub.js";
|
|
2
|
+
import { ClearModel, type Variant } from "./model.js";
|
|
3
|
+
export { ClearModel, SR } from "./model.js";
|
|
4
|
+
export type { EnhanceOptions, EnhanceResult, EnhanceStage, ProgressFn, Variant } from "./model.js";
|
|
5
|
+
export { setOrt } from "./ort.js";
|
|
6
|
+
export type { Ort } from "./ort.js";
|
|
7
|
+
export { decodeToMono } from "./decode-web.js";
|
|
8
|
+
export { encodeWav, decodeWav } from "./wav.js";
|
|
9
|
+
export type { DecodedWav } from "./wav.js";
|
|
10
|
+
export { applyLimiter, measureLUFS, MASTERING_PRESETS, resolveMastering } from "./r128.js";
|
|
11
|
+
export type { MasteringConfig, MasteringPreset, MasteringSpec } from "./r128.js";
|
|
12
|
+
export { loadModelBytes, DEFAULT_HOST, DEFAULT_REPO, DEFAULT_REVISION, MODEL_FILES } from "./hub.js";
|
|
13
|
+
export type { ClearEnv, FileCache, DownloadProgress } from "./hub.js";
|
|
14
|
+
/** Bare specifier of the ONNX Runtime used in browsers/workers. */
|
|
15
|
+
export declare const ORT_SPECIFIER = "onnxruntime-web";
|
|
16
|
+
/** Loading configuration. Mutate before the first {@link load}, or pass overrides. */
|
|
17
|
+
export declare const env: ClearEnv;
|
|
18
|
+
export interface LoadOptions extends Partial<ClearEnv> {
|
|
19
|
+
/** Quality variant. `"studio"` (default) or `"natural"`. */
|
|
20
|
+
variant?: Variant;
|
|
21
|
+
/** Skip WebGPU even when available. */
|
|
22
|
+
forceWasm?: boolean;
|
|
23
|
+
/** Override the WASM thread count (lower eases SharedArrayBuffer pressure). */
|
|
24
|
+
numThreads?: number;
|
|
25
|
+
/** Model download progress. */
|
|
26
|
+
onDownloadProgress?: DownloadProgress;
|
|
27
|
+
/** Compilation-phase notifications. */
|
|
28
|
+
onPhase?: (phase: "compiling-webgpu" | "compiling-wasm") => void;
|
|
29
|
+
}
|
|
30
|
+
/** Loads a variant from the Hugging Face Hub (cached in Cache Storage) and builds a session. */
|
|
31
|
+
export declare function load(options?: LoadOptions): Promise<ClearModel>;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Browser / Worker entry. Fetches the model from the Hugging Face Hub (cached
|
|
3
|
+
// in Cache Storage) and runs it through onnxruntime-web (WebGPU when
|
|
4
|
+
// available, threaded WASM otherwise).
|
|
5
|
+
import { webCache } from "./cache-web.js";
|
|
6
|
+
import { DEFAULT_HOST, DEFAULT_REPO, DEFAULT_REVISION, loadModelBytes } from "./hub.js";
|
|
7
|
+
import { ClearModel } from "./model.js";
|
|
8
|
+
import { resolveOrt } from "./ort.js";
|
|
9
|
+
export { ClearModel, SR } from "./model.js";
|
|
10
|
+
export { setOrt } from "./ort.js";
|
|
11
|
+
export { decodeToMono } from "./decode-web.js";
|
|
12
|
+
export { encodeWav, decodeWav } from "./wav.js";
|
|
13
|
+
export { applyLimiter, measureLUFS, MASTERING_PRESETS, resolveMastering } from "./r128.js";
|
|
14
|
+
export { loadModelBytes, DEFAULT_HOST, DEFAULT_REPO, DEFAULT_REVISION, MODEL_FILES } from "./hub.js";
|
|
15
|
+
/** Bare specifier of the ONNX Runtime used in browsers/workers. */
|
|
16
|
+
export const ORT_SPECIFIER = "onnxruntime-web";
|
|
17
|
+
/** Loading configuration. Mutate before the first {@link load}, or pass overrides. */
|
|
18
|
+
export const env = {
|
|
19
|
+
host: DEFAULT_HOST,
|
|
20
|
+
repo: DEFAULT_REPO,
|
|
21
|
+
revision: DEFAULT_REVISION,
|
|
22
|
+
allowRemote: true,
|
|
23
|
+
useCache: true,
|
|
24
|
+
};
|
|
25
|
+
/** Loads a variant from the Hugging Face Hub (cached in Cache Storage) and builds a session. */
|
|
26
|
+
export async function load(options = {}) {
|
|
27
|
+
const variant = options.variant ?? "studio";
|
|
28
|
+
const e = { ...env, ...options };
|
|
29
|
+
const cache = e.useCache ? webCache() : null;
|
|
30
|
+
const bytes = await loadModelBytes(e, variant, cache, undefined, options.onDownloadProgress);
|
|
31
|
+
const ort = await resolveOrt(ORT_SPECIFIER);
|
|
32
|
+
const ortEnv = (ort.env ?? {});
|
|
33
|
+
ortEnv.logLevel = "error";
|
|
34
|
+
const wasm = (ortEnv.wasm ?? (ortEnv.wasm = {}));
|
|
35
|
+
wasm.simd = true;
|
|
36
|
+
const nav = globalThis.navigator;
|
|
37
|
+
const isSafari = nav?.userAgent ? /^((?!chrome|android).)*safari/i.test(nav.userAgent) : false;
|
|
38
|
+
const crossOriginIsolated = globalThis.crossOriginIsolated === true;
|
|
39
|
+
const autoThreads = crossOriginIsolated && !isSafari ? Math.min(4, nav?.hardwareConcurrency || 1) : 1;
|
|
40
|
+
wasm.numThreads = options.numThreads ?? autoThreads;
|
|
41
|
+
const sessionOptions = {
|
|
42
|
+
enableMemPattern: false,
|
|
43
|
+
enableCpuMemArena: false,
|
|
44
|
+
executionMode: "sequential",
|
|
45
|
+
graphOptimizationLevel: "all",
|
|
46
|
+
};
|
|
47
|
+
let session = null;
|
|
48
|
+
let backend = "wasm";
|
|
49
|
+
if (nav && "gpu" in nav && !options.forceWasm) {
|
|
50
|
+
options.onPhase?.("compiling-webgpu");
|
|
51
|
+
try {
|
|
52
|
+
session = await ort.InferenceSession.create(bytes, { executionProviders: ["webgpu"], ...sessionOptions });
|
|
53
|
+
backend = "webgpu";
|
|
54
|
+
}
|
|
55
|
+
catch (e2) {
|
|
56
|
+
// Fall back to WASM.
|
|
57
|
+
console.warn("[clear] WebGPU init failed, falling back to WASM:", e2?.message ?? e2);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (!session) {
|
|
61
|
+
options.onPhase?.("compiling-wasm");
|
|
62
|
+
session = await ort.InferenceSession.create(bytes, { executionProviders: ["wasm"], ...sessionOptions });
|
|
63
|
+
}
|
|
64
|
+
return new ClearModel({ ort, session, variant, backend, yieldFn: yieldToBrowser });
|
|
65
|
+
}
|
|
66
|
+
function yieldToBrowser() {
|
|
67
|
+
const raf = globalThis.requestAnimationFrame;
|
|
68
|
+
if (typeof raf === "function")
|
|
69
|
+
return new Promise((r) => raf(() => r()));
|
|
70
|
+
return new Promise((r) => setTimeout(r, 0));
|
|
71
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type ClearEnv, type DownloadProgress } from "./hub.js";
|
|
2
|
+
import { ClearModel, type Variant } from "./model.js";
|
|
3
|
+
export { ClearModel, SR } from "./model.js";
|
|
4
|
+
export type { EnhanceOptions, EnhanceResult, EnhanceStage, ProgressFn, Variant } from "./model.js";
|
|
5
|
+
export { setOrt } from "./ort.js";
|
|
6
|
+
export type { Ort } from "./ort.js";
|
|
7
|
+
export { encodeWav, decodeWav } from "./wav.js";
|
|
8
|
+
export type { DecodedWav } from "./wav.js";
|
|
9
|
+
export { applyLimiter, measureLUFS, MASTERING_PRESETS, resolveMastering } from "./r128.js";
|
|
10
|
+
export type { MasteringConfig, MasteringPreset, MasteringSpec } from "./r128.js";
|
|
11
|
+
export { loadModelBytes, DEFAULT_HOST, DEFAULT_REPO, DEFAULT_REVISION, MODEL_FILES } from "./hub.js";
|
|
12
|
+
export type { ClearEnv, FileCache, DownloadProgress } from "./hub.js";
|
|
13
|
+
/** Bare specifier of the ONNX Runtime used on the server. */
|
|
14
|
+
export declare const ORT_SPECIFIER = "onnxruntime-node";
|
|
15
|
+
/** Loading configuration. Mutate before the first {@link load}, or pass overrides. */
|
|
16
|
+
export declare const env: ClearEnv;
|
|
17
|
+
export interface LoadOptions extends Partial<ClearEnv> {
|
|
18
|
+
/** Quality variant. `"studio"` (default) or `"natural"`. */
|
|
19
|
+
variant?: Variant;
|
|
20
|
+
/** Model download progress. */
|
|
21
|
+
onDownloadProgress?: DownloadProgress;
|
|
22
|
+
}
|
|
23
|
+
/** Loads a variant (local dir → disk cache → Hugging Face Hub) and builds a CPU session. */
|
|
24
|
+
export declare function load(options?: LoadOptions): Promise<ClearModel>;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Node / server entry. Fetches the model from the Hugging Face Hub (cached to
|
|
3
|
+
// disk) and runs it through onnxruntime-node on the CPU. Audio input is a
|
|
4
|
+
// mono Float32Array at 48 kHz — use `decodeWav` for WAV buffers, or decode
|
|
5
|
+
// compressed formats upstream.
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { fsCache, localReader } from "./cache-node.js";
|
|
9
|
+
import { DEFAULT_HOST, DEFAULT_REPO, DEFAULT_REVISION, loadModelBytes } from "./hub.js";
|
|
10
|
+
import { ClearModel } from "./model.js";
|
|
11
|
+
import { resolveOrt } from "./ort.js";
|
|
12
|
+
export { ClearModel, SR } from "./model.js";
|
|
13
|
+
export { setOrt } from "./ort.js";
|
|
14
|
+
export { encodeWav, decodeWav } from "./wav.js";
|
|
15
|
+
export { applyLimiter, measureLUFS, MASTERING_PRESETS, resolveMastering } from "./r128.js";
|
|
16
|
+
export { loadModelBytes, DEFAULT_HOST, DEFAULT_REPO, DEFAULT_REVISION, MODEL_FILES } from "./hub.js";
|
|
17
|
+
/** Bare specifier of the ONNX Runtime used on the server. */
|
|
18
|
+
export const ORT_SPECIFIER = "onnxruntime-node";
|
|
19
|
+
/** Loading configuration. Mutate before the first {@link load}, or pass overrides. */
|
|
20
|
+
export const env = {
|
|
21
|
+
host: DEFAULT_HOST,
|
|
22
|
+
repo: DEFAULT_REPO,
|
|
23
|
+
revision: DEFAULT_REVISION,
|
|
24
|
+
allowRemote: true,
|
|
25
|
+
useCache: true,
|
|
26
|
+
cacheDir: process.env.CLEAR_CACHE_DIR ?? join(homedir(), ".cache", "clear"),
|
|
27
|
+
localModelPath: process.env.CLEAR_LOCAL_PATH,
|
|
28
|
+
token: process.env.HF_TOKEN ?? process.env.HUGGING_FACE_HUB_TOKEN,
|
|
29
|
+
};
|
|
30
|
+
/** Loads a variant (local dir → disk cache → Hugging Face Hub) and builds a CPU session. */
|
|
31
|
+
export async function load(options = {}) {
|
|
32
|
+
const variant = options.variant ?? "studio";
|
|
33
|
+
const e = { ...env, ...options };
|
|
34
|
+
const cache = e.useCache && e.cacheDir ? fsCache(e.cacheDir) : null;
|
|
35
|
+
const readLocal = e.localModelPath ? localReader(e.localModelPath) : undefined;
|
|
36
|
+
const bytes = await loadModelBytes(e, variant, cache, readLocal, options.onDownloadProgress);
|
|
37
|
+
const ort = await resolveOrt(ORT_SPECIFIER);
|
|
38
|
+
const session = await ort.InferenceSession.create(bytes, {
|
|
39
|
+
executionProviders: ["cpu"],
|
|
40
|
+
executionMode: "sequential",
|
|
41
|
+
graphOptimizationLevel: "all",
|
|
42
|
+
});
|
|
43
|
+
return new ClearModel({ ort, session, variant, backend: "cpu" });
|
|
44
|
+
}
|
package/dist/model.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { Ort, OrtSession } from "./ort.js";
|
|
2
|
+
import { type MasteringSpec } from "./r128.js";
|
|
3
|
+
/** Model sample rate. Inputs must be mono PCM at this rate. */
|
|
4
|
+
export declare const SR = 48000;
|
|
5
|
+
export type Variant = "studio" | "natural";
|
|
6
|
+
export type EnhanceStage = "inference" | "mastering";
|
|
7
|
+
export type ProgressFn = (stage: EnhanceStage, value: number, ctx?: {
|
|
8
|
+
chunk: number;
|
|
9
|
+
totalChunks: number;
|
|
10
|
+
}) => void;
|
|
11
|
+
export interface EnhanceOptions {
|
|
12
|
+
/**
|
|
13
|
+
* Loudness target. Defaults to Apple Podcasts (−19 LUFS, −1.5 dBTP).
|
|
14
|
+
* Pass `"bypass"` / `null` for raw model output.
|
|
15
|
+
*/
|
|
16
|
+
mastering?: MasteringSpec;
|
|
17
|
+
/** Progress callback across inference chunks and the mastering pass. */
|
|
18
|
+
onProgress?: ProgressFn;
|
|
19
|
+
}
|
|
20
|
+
export interface EnhanceResult {
|
|
21
|
+
/** Enhanced mono PCM at 48 kHz. */
|
|
22
|
+
audio: Float32Array;
|
|
23
|
+
durationSec: number;
|
|
24
|
+
sampleRate: number;
|
|
25
|
+
/** Integrated loudness of the output, or `null` when mastering is bypassed. */
|
|
26
|
+
measuredLUFS: number | null;
|
|
27
|
+
/** True-peak ceiling enforced, or `null` when mastering is bypassed. */
|
|
28
|
+
measuredTruePeakDBFS: number | null;
|
|
29
|
+
}
|
|
30
|
+
export interface ClearModelInit {
|
|
31
|
+
ort: Ort;
|
|
32
|
+
session: OrtSession;
|
|
33
|
+
variant: Variant;
|
|
34
|
+
/** Execution provider in use, e.g. `"webgpu"`, `"wasm"`, `"cpu"`. */
|
|
35
|
+
backend: string;
|
|
36
|
+
/** Cooperative yield between chunks (the browser uses requestAnimationFrame). */
|
|
37
|
+
yieldFn?: () => Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
/** A loaded model. Reuse across many `enhance` calls; `dispose` when done. */
|
|
40
|
+
export declare class ClearModel {
|
|
41
|
+
#private;
|
|
42
|
+
constructor(init: ClearModelInit);
|
|
43
|
+
get backend(): string;
|
|
44
|
+
get variant(): Variant;
|
|
45
|
+
get sampleRate(): number;
|
|
46
|
+
/** Enhance mono PCM at 48 kHz. */
|
|
47
|
+
enhance(pcm: Float32Array, options?: EnhanceOptions): Promise<EnhanceResult>;
|
|
48
|
+
/** Free the model session. Safe to call multiple times. */
|
|
49
|
+
dispose(): Promise<void>;
|
|
50
|
+
}
|
package/dist/model.js
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Core speech-enhancement model. Platform-agnostic: it takes a loaded ONNX
|
|
3
|
+
// Runtime session and operates on mono Float32 PCM at 48 kHz.
|
|
4
|
+
//
|
|
5
|
+
// Pipeline: STFT → erb + complex-spec features → chunked ONNX (T=200
|
|
6
|
+
// frames) → ISTFT → optional R128 mastering.
|
|
7
|
+
import { N_ERB } from "./erb.js";
|
|
8
|
+
import { computeFeatures, N_DF } from "./features.js";
|
|
9
|
+
import { applyLimiter, measureLUFS, MODEL_ATTENUATION_DB, resolveMastering, } from "./r128.js";
|
|
10
|
+
import { FFT_SIZE, HOP_SIZE, N_FREQ, STFT } from "./stft.js";
|
|
11
|
+
/** Model sample rate. Inputs must be mono PCM at this rate. */
|
|
12
|
+
export const SR = 48_000;
|
|
13
|
+
const T_FIXED = 200;
|
|
14
|
+
const CONV_LOOKAHEAD = 2;
|
|
15
|
+
/** A loaded model. Reuse across many `enhance` calls; `dispose` when done. */
|
|
16
|
+
export class ClearModel {
|
|
17
|
+
#ort;
|
|
18
|
+
#session;
|
|
19
|
+
#variant;
|
|
20
|
+
#backend;
|
|
21
|
+
#stft;
|
|
22
|
+
#yield;
|
|
23
|
+
constructor(init) {
|
|
24
|
+
this.#ort = init.ort;
|
|
25
|
+
this.#session = init.session;
|
|
26
|
+
this.#variant = init.variant;
|
|
27
|
+
this.#backend = init.backend;
|
|
28
|
+
this.#stft = new STFT(FFT_SIZE, HOP_SIZE);
|
|
29
|
+
this.#yield = init.yieldFn ?? (() => Promise.resolve());
|
|
30
|
+
}
|
|
31
|
+
get backend() {
|
|
32
|
+
return this.#backend;
|
|
33
|
+
}
|
|
34
|
+
get variant() {
|
|
35
|
+
return this.#variant;
|
|
36
|
+
}
|
|
37
|
+
get sampleRate() {
|
|
38
|
+
return SR;
|
|
39
|
+
}
|
|
40
|
+
/** Enhance mono PCM at 48 kHz. */
|
|
41
|
+
async enhance(pcm, options = {}) {
|
|
42
|
+
const session = this.#session;
|
|
43
|
+
if (!session)
|
|
44
|
+
throw new Error("clear: model has been disposed");
|
|
45
|
+
const onProgress = options.onProgress;
|
|
46
|
+
const mastering = resolveMastering(options.mastering === undefined ? "applePodcasts" : options.mastering);
|
|
47
|
+
const sanitized = sanitize(pcm);
|
|
48
|
+
let inputLUFS = Infinity;
|
|
49
|
+
if (mastering.enabled)
|
|
50
|
+
inputLUFS = measureLUFS(sanitized, SR);
|
|
51
|
+
const padded = padToWindowMultiple(sanitized);
|
|
52
|
+
const { real, imag, nFrames } = this.#stft.forward(padded);
|
|
53
|
+
if (nFrames === 0) {
|
|
54
|
+
return {
|
|
55
|
+
audio: sanitized,
|
|
56
|
+
durationSec: sanitized.length / SR,
|
|
57
|
+
sampleRate: SR,
|
|
58
|
+
measuredLUFS: null,
|
|
59
|
+
measuredTruePeakDBFS: null,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
const { featErb, featSpecReal, featSpecImag } = computeFeatures(real, imag, nFrames, N_FREQ);
|
|
63
|
+
const enhancedReal = new Float32Array(real.length);
|
|
64
|
+
const enhancedImag = new Float32Array(imag.length);
|
|
65
|
+
const T = T_FIXED;
|
|
66
|
+
const nChunks = Math.ceil(nFrames / T);
|
|
67
|
+
const specBuf = new Float32Array(T * N_FREQ * 2);
|
|
68
|
+
const erbBuf = new Float32Array(T * N_ERB);
|
|
69
|
+
const dfBuf = new Float32Array(T * N_DF * 2);
|
|
70
|
+
for (let c = 0; c < nChunks; c++) {
|
|
71
|
+
const start = c * T;
|
|
72
|
+
const end = Math.min(start + T, nFrames);
|
|
73
|
+
await this.#runChunk(session, start, end, nFrames, real, imag, featErb, featSpecReal, featSpecImag, enhancedReal, enhancedImag, specBuf, erbBuf, dfBuf);
|
|
74
|
+
onProgress?.("inference", (c + 1) / nChunks, { chunk: c + 1, totalChunks: nChunks });
|
|
75
|
+
await this.#yield();
|
|
76
|
+
}
|
|
77
|
+
const enhancedTime = this.#stft.inverse(enhancedReal, enhancedImag, nFrames);
|
|
78
|
+
let out = enhancedTime.slice(0, sanitized.length);
|
|
79
|
+
let measuredLUFS = null;
|
|
80
|
+
let measuredTP = null;
|
|
81
|
+
if (mastering.enabled && Number.isFinite(inputLUFS)) {
|
|
82
|
+
onProgress?.("mastering", 0);
|
|
83
|
+
const predictedEnhancedLUFS = inputLUFS - MODEL_ATTENUATION_DB;
|
|
84
|
+
const requestedGainDB = mastering.integratedLUFS - predictedEnhancedLUFS;
|
|
85
|
+
const effectiveGainDB = Math.min(requestedGainDB, mastering.maxLoudnessGainDB);
|
|
86
|
+
const masterGain = Math.pow(10, effectiveGainDB / 20);
|
|
87
|
+
for (let i = 0; i < out.length; i++)
|
|
88
|
+
out[i] *= masterGain;
|
|
89
|
+
out = applyLimiter(out, SR, mastering.truePeakDBTP);
|
|
90
|
+
measuredLUFS = predictedEnhancedLUFS + effectiveGainDB;
|
|
91
|
+
measuredTP = mastering.truePeakDBTP;
|
|
92
|
+
onProgress?.("mastering", 1);
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
audio: out,
|
|
96
|
+
durationSec: out.length / SR,
|
|
97
|
+
sampleRate: SR,
|
|
98
|
+
measuredLUFS,
|
|
99
|
+
measuredTruePeakDBFS: measuredTP,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
async #runChunk(session, start, end, nFrames, specReal, specImag, featErb, featSpecReal, featSpecImag, outReal, outImag, specBuf, erbBuf, dfBuf) {
|
|
103
|
+
const T = T_FIXED;
|
|
104
|
+
const nErb = N_ERB;
|
|
105
|
+
const nDf = N_DF;
|
|
106
|
+
const nFreq = N_FREQ;
|
|
107
|
+
specBuf.fill(0);
|
|
108
|
+
erbBuf.fill(0);
|
|
109
|
+
dfBuf.fill(0);
|
|
110
|
+
// Lookahead shift: chunk frame t reads featGlobal[start + t + CONV_LOOKAHEAD].
|
|
111
|
+
const tStart = Math.max(0, -start - CONV_LOOKAHEAD);
|
|
112
|
+
const tEnd = Math.min(T, nFrames - start - CONV_LOOKAHEAD);
|
|
113
|
+
if (tEnd > tStart) {
|
|
114
|
+
const srcFrameStart = start + tStart + CONV_LOOKAHEAD;
|
|
115
|
+
erbBuf.set(featErb.subarray(srcFrameStart * nErb, (srcFrameStart + (tEnd - tStart)) * nErb), tStart * nErb);
|
|
116
|
+
for (let t = 0; t < tEnd - tStart; t++) {
|
|
117
|
+
const srcOff = (srcFrameStart + t) * nDf;
|
|
118
|
+
const dstOff = (tStart + t) * nDf * 2;
|
|
119
|
+
for (let f = 0; f < nDf; f++) {
|
|
120
|
+
dfBuf[dstOff + f * 2] = featSpecReal[srcOff + f];
|
|
121
|
+
dfBuf[dstOff + f * 2 + 1] = featSpecImag[srcOff + f];
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
// Pack raw spec for this chunk into [B=1, C=1, T, F, 2].
|
|
126
|
+
const sStart = Math.max(0, -start);
|
|
127
|
+
const sEnd = Math.min(T, nFrames - start);
|
|
128
|
+
if (sEnd > sStart) {
|
|
129
|
+
const srcFrameStart = start + sStart;
|
|
130
|
+
for (let t = 0; t < sEnd - sStart; t++) {
|
|
131
|
+
const srcOff = (srcFrameStart + t) * nFreq;
|
|
132
|
+
const dstOff = (sStart + t) * nFreq * 2;
|
|
133
|
+
for (let f = 0; f < nFreq; f++) {
|
|
134
|
+
specBuf[dstOff + f * 2] = specReal[srcOff + f];
|
|
135
|
+
specBuf[dstOff + f * 2 + 1] = specImag[srcOff + f];
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const Tensor = this.#ort.Tensor;
|
|
140
|
+
const feeds = {
|
|
141
|
+
spec: new Tensor("float32", specBuf, [1, 1, T, nFreq, 2]),
|
|
142
|
+
feat_erb: new Tensor("float32", erbBuf, [1, 1, T, nErb]),
|
|
143
|
+
feat_spec: new Tensor("float32", dfBuf, [1, 1, T, nDf, 2]),
|
|
144
|
+
};
|
|
145
|
+
const results = await session.run(feeds);
|
|
146
|
+
const spec_enhanced = results.spec_enhanced;
|
|
147
|
+
const enhanced = spec_enhanced.data;
|
|
148
|
+
const validFrames = end - start;
|
|
149
|
+
for (let t = 0; t < validFrames; t++) {
|
|
150
|
+
const srcOff = t * nFreq * 2;
|
|
151
|
+
const dstOff = (start + t) * nFreq;
|
|
152
|
+
for (let f = 0; f < nFreq; f++) {
|
|
153
|
+
outReal[dstOff + f] = enhanced[srcOff + f * 2];
|
|
154
|
+
outImag[dstOff + f] = enhanced[srcOff + f * 2 + 1];
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
spec_enhanced.dispose?.();
|
|
158
|
+
}
|
|
159
|
+
/** Free the model session. Safe to call multiple times. */
|
|
160
|
+
async dispose() {
|
|
161
|
+
try {
|
|
162
|
+
await this.#session?.release?.();
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
/* best-effort */
|
|
166
|
+
}
|
|
167
|
+
this.#session = null;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
function sanitize(samples) {
|
|
171
|
+
let nonFinite = false;
|
|
172
|
+
for (let i = 0; i < samples.length; i++) {
|
|
173
|
+
if (!Number.isFinite(samples[i])) {
|
|
174
|
+
nonFinite = true;
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
if (!nonFinite)
|
|
179
|
+
return samples;
|
|
180
|
+
const out = new Float32Array(samples);
|
|
181
|
+
for (let i = 0; i < out.length; i++) {
|
|
182
|
+
if (!Number.isFinite(out[i]))
|
|
183
|
+
out[i] = 0;
|
|
184
|
+
}
|
|
185
|
+
return out;
|
|
186
|
+
}
|
|
187
|
+
function padToWindowMultiple(samples) {
|
|
188
|
+
const needed = Math.max(FFT_SIZE, Math.ceil(samples.length / HOP_SIZE) * HOP_SIZE + FFT_SIZE);
|
|
189
|
+
if (samples.length >= needed)
|
|
190
|
+
return samples;
|
|
191
|
+
const out = new Float32Array(needed);
|
|
192
|
+
out.set(samples);
|
|
193
|
+
return out;
|
|
194
|
+
}
|