@suarify/kecil-tts 0.0.0-stage → 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/src/index.js ADDED
@@ -0,0 +1,224 @@
1
+ // @suarify/kecil-tts — Malay text-to-speech for browsers and Node.js.
2
+ // Runs the small ONNX models from https://huggingface.co/Suarify locally:
3
+ // nothing is sent to a server and no API key is needed.
4
+ import {
5
+ Suaradee,
6
+ KecilTTS,
7
+ DEFAULT_MODEL,
8
+ SAMPLE_RATE,
9
+ FIRST_MAX,
10
+ LATER_MAX,
11
+ G2P_OPTIONS,
12
+ splitSentences,
13
+ } from './tts.js';
14
+ import { encodeWav, concatFloat32 } from './wav.js';
15
+ import { applyEffects } from './effects.js';
16
+ import { runtimeInfo, checkOnnxRuntime } from './runtime.js';
17
+
18
+ export {
19
+ Suaradee,
20
+ KecilTTS,
21
+ DEFAULT_MODEL,
22
+ SAMPLE_RATE,
23
+ FIRST_MAX,
24
+ LATER_MAX,
25
+ G2P_OPTIONS,
26
+ splitSentences,
27
+ encodeWav,
28
+ concatFloat32,
29
+ };
30
+ export { G2P, normalize, chunk, createG2P } from './g2p/index.js';
31
+ export { runtimeInfo, checkOnnxRuntime } from './runtime.js';
32
+ export {
33
+ FX_PARAMETERS,
34
+ FX_DEFAULTS,
35
+ FX_PRESETS,
36
+ applyEffects,
37
+ listFxParameters,
38
+ listFxPresets,
39
+ } from './effects.js';
40
+
41
+ // All versions offered by the Kecil-TTS web Space.
42
+ export const VOICE_VERSIONS = Object.freeze({
43
+ yati: Object.freeze([
44
+ { id: 'Suarify/kecil-tts-yati-v0.5.0', label: 'v0.5 (latest)' },
45
+ { id: 'Suarify/kecil-tts-yati-v0.4.1', label: 'v0.4.1' },
46
+ { id: 'Suarify/kecil-tts-yati-v0.4', label: 'v0.4' },
47
+ { id: 'Suarify/kecil-tts-yati-v0.3', label: 'v0.3' },
48
+ { id: 'Suarify/kecil-tts-yati-v0.2', label: 'v0.2' },
49
+ { id: 'Suarify/kecil-tts-yati-v0.1', label: 'v0.1' },
50
+ ]),
51
+ michael: Object.freeze([
52
+ { id: 'Suarify/kecil-tts-michael-v0.3.1', label: 'v0.3.1 (latest)' },
53
+ { id: 'Suarify/kecil-tts-michael-v0.3.0', label: 'v0.3.0' },
54
+ { id: 'Suarify/kecil-tts-michael-v0.2.2', label: 'v0.2.2' },
55
+ { id: 'Suarify/kecil-tts-michael-v0.2', label: 'v0.2' },
56
+ { id: 'Suarify/kecil-tts-michael-v0.1', label: 'v0.1' },
57
+ ]),
58
+ firdaus: Object.freeze([
59
+ { id: 'Suarify/kecil-tts-firdaus-v0.1', label: 'v0.1' },
60
+ ]),
61
+ nicole: Object.freeze([
62
+ { id: 'Suarify/kecil-tts-nicole-v0.2', label: 'v0.2 (latest)' },
63
+ { id: 'Suarify/kecil-tts-nicole-v0.1', label: 'v0.1' },
64
+ ]),
65
+ });
66
+
67
+ const voiceInfo = (key, name, gender, sub, card, note) => Object.freeze({
68
+ name,
69
+ gender,
70
+ sub,
71
+ card,
72
+ note,
73
+ model: VOICE_VERSIONS[key][0].id,
74
+ });
75
+
76
+ export const VOICES = Object.freeze({
77
+ yati: voiceInfo('yati', 'Yati', 'female', 'female voice · default',
78
+ 'https://huggingface.co/Suarify/kecil-tts-yati-v0.5.0',
79
+ 'Default speaker. v0.5 is the latest release.'),
80
+ michael: voiceInfo('michael', 'Michael', 'male', 'male voice · new',
81
+ 'https://huggingface.co/Suarify/kecil-tts-michael-v0.3.1',
82
+ 'v0.3.1 fixes the slow timing of v0.3.0 with training-faithful synthesis.'),
83
+ firdaus: voiceInfo('firdaus', 'Firdaus', 'male', 'male voice · early release',
84
+ 'https://huggingface.co/Suarify/kecil-tts-firdaus-v0.1',
85
+ 'Built from Yati v0.5. v0.1 sounds robotic — published for feedback.'),
86
+ nicole: voiceInfo('nicole', 'Nicole', 'female', 'female voice',
87
+ 'https://huggingface.co/Suarify/kecil-tts-nicole-v0.2',
88
+ 'Rebuilt from Yati v0.5 with fixed loudness and +25% volume.'),
89
+ });
90
+
91
+ export const DEFAULT_VOICE = 'yati';
92
+
93
+ const instances = new Map();
94
+
95
+ // Resolve a model id from voice, version label/id or an explicit repo id.
96
+ export function resolveModel(voice, { version, model } = {}) {
97
+ if (model) return model;
98
+ if (!voice) return DEFAULT_MODEL;
99
+ const info = VOICES[voice];
100
+ if (!info) throw new Error(`Unknown voice "${voice}". Choose one of: ${Object.keys(VOICES).join(', ')}`);
101
+ if (version) {
102
+ const found = VOICE_VERSIONS[voice].find((v) => v.id === version || v.label === version);
103
+ if (!found) throw new Error(`Unknown version "${version}" for ${voice}. Choose one of: ${VOICE_VERSIONS[voice].map((v) => v.label).join(', ')}`);
104
+ return found.id;
105
+ }
106
+ return info.model;
107
+ }
108
+
109
+ let runtimeCheck;
110
+ async function assertRuntime() {
111
+ if (typeof process === 'undefined' || !process.versions?.node) return;
112
+ if (!runtimeCheck) runtimeCheck = checkOnnxRuntime();
113
+ const result = await runtimeCheck;
114
+ if (!result.ok) {
115
+ throw new Error(`KecilTTS: native ONNX runtime unavailable (${result.error}). ${result.suggestion}`);
116
+ }
117
+ }
118
+
119
+ // Load (and reuse) a synthesized model instance.
120
+ export async function loadTTS(options = {}) {
121
+ await assertRuntime();
122
+ const {
123
+ voice = DEFAULT_VOICE,
124
+ model,
125
+ version,
126
+ device = 'auto',
127
+ dtype = 'q8',
128
+ local = false,
129
+ modelRoot,
130
+ sessionOptions,
131
+ progressCallback,
132
+ g2p,
133
+ } = options;
134
+
135
+ const id = resolveModel(voice, { model, version });
136
+ const key = JSON.stringify([id, device, dtype, local, modelRoot ?? null]);
137
+ let pending = instances.get(key);
138
+ if (!pending) {
139
+ pending = KecilTTS.load({ model: id, device, dtype, local, modelRoot, sessionOptions, progressCallback, g2p });
140
+ instances.set(key, pending);
141
+ pending.catch(() => instances.delete(key));
142
+ }
143
+ return pending;
144
+ }
145
+
146
+ function splitOptions(options) {
147
+ const {
148
+ voice, model, version, device, dtype, local, modelRoot, sessionOptions, progressCallback, g2p,
149
+ speed = 1.0, pause = 0.12, firstMax = FIRST_MAX, effects,
150
+ } = options;
151
+ return {
152
+ load: { voice, model, version, device, dtype, local, modelRoot, sessionOptions, progressCallback, g2p },
153
+ synth: { speed, pause, firstMax },
154
+ effects,
155
+ };
156
+ }
157
+
158
+ // All speakers and every published version, ready for a dropdown or API response.
159
+ export function listVoices() {
160
+ return Object.entries(VOICES).map(([key, info]) => ({
161
+ key,
162
+ name: info.name,
163
+ gender: info.gender,
164
+ sub: info.sub,
165
+ note: info.note,
166
+ card: info.card,
167
+ defaultVersion: VOICE_VERSIONS[key][0].label,
168
+ versions: VOICE_VERSIONS[key].map((v) => ({ ...v })),
169
+ }));
170
+ }
171
+
172
+ // Versions for one speaker (or every speaker when no key is given).
173
+ export function listVersions(voice) {
174
+ if (voice) {
175
+ if (!VOICE_VERSIONS[voice]) throw new Error(`Unknown voice "${voice}". Choose one of: ${Object.keys(VOICES).join(', ')}`);
176
+ return VOICE_VERSIONS[voice].map((v) => ({ ...v }));
177
+ }
178
+ return Object.fromEntries(Object.entries(VOICE_VERSIONS).map(([k, v]) => [k, v.map((x) => ({ ...x }))]));
179
+ }
180
+
181
+ // Browser helper: save PCM or a WAV ArrayBuffer as a downloaded .wav file.
182
+ export function downloadWav(wavOrAudio, options = {}) {
183
+ if (typeof document === 'undefined') throw new Error('downloadWav() only works in a browser. In Node use writeFileSync(path, Buffer.from(wav)).');
184
+ const { filename = 'kecil-tts.wav', sampleRate = SAMPLE_RATE } = options;
185
+ const buffer = wavOrAudio instanceof ArrayBuffer ? wavOrAudio : encodeWav(wavOrAudio, sampleRate);
186
+ const url = URL.createObjectURL(new Blob([buffer], { type: 'audio/wav' }));
187
+ const a = document.createElement('a');
188
+ a.href = url;
189
+ a.download = filename;
190
+ document.body.appendChild(a);
191
+ a.click();
192
+ a.remove();
193
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
194
+ return filename;
195
+ }
196
+
197
+ // One-shot synthesis. Returns float32 PCM plus a ready-to-use WAV ArrayBuffer.
198
+ export async function speak(text, options = {}) {
199
+ const { load, synth, effects } = splitOptions(options);
200
+ const tts = await loadTTS(load);
201
+ const result = await tts.speak(text, synth);
202
+ const audio = effects ? applyEffects(result.audio, { sampleRate: result.sampleRate, effects }) : result.audio;
203
+ return { audio, sampleRate: result.sampleRate, wav: encodeWav(audio, result.sampleRate) };
204
+ }
205
+
206
+ // Incremental synthesis: yields one Float32Array per piece as soon as it is ready.
207
+ // Effects are stateful, so use speak()/speakPCM() when applying them, or collect
208
+ // the chunks and call applyEffects() on the result yourself.
209
+ export async function* stream(text, options = {}) {
210
+ const { load, synth } = splitOptions(options);
211
+ const tts = await loadTTS(load);
212
+ yield* tts.stream(text, synth);
213
+ }
214
+
215
+ // Collect a stream into a single Float32Array (useful when you want PCM without WAV).
216
+ export async function speakPCM(text, options = {}) {
217
+ const chunks = [];
218
+ for await (const chunk of stream(text, options)) chunks.push(chunk);
219
+ const audio = concatFloat32(chunks);
220
+ return {
221
+ audio: options.effects ? applyEffects(audio, { sampleRate: SAMPLE_RATE, effects: options.effects }) : audio,
222
+ sampleRate: SAMPLE_RATE,
223
+ };
224
+ }
package/src/runtime.js ADDED
@@ -0,0 +1,44 @@
1
+ // Server-side runtime checks for the native ONNX backend used by transformers.js in Node.
2
+ // Browsers do not need this: they use onnxruntime-web (WASM / WebGPU).
3
+
4
+ export function runtimeInfo() {
5
+ if (typeof process === 'undefined' || !process.versions?.node) {
6
+ return { node: false, backend: 'onnxruntime-web (WASM / WebGPU)' };
7
+ }
8
+ const platform = process.platform;
9
+ const arch = process.arch;
10
+ const supported = (
11
+ (platform === 'win32' && (arch === 'x64' || arch === 'arm64')) ||
12
+ (platform === 'linux' && (arch === 'x64' || arch === 'arm64')) ||
13
+ (platform === 'darwin' && (arch === 'x64' || arch === 'arm64'))
14
+ );
15
+ return {
16
+ node: true,
17
+ version: process.versions.node,
18
+ platform,
19
+ arch,
20
+ backend: 'onnxruntime-node (CPU)',
21
+ supported,
22
+ hint: supported
23
+ ? 'Node 20+, onnxruntime-node native binaries and (on Windows) the Visual C++ runtime are required.'
24
+ : 'This platform/architecture has no onnxruntime-node prebuilt binary. Use a browser or the Python package instead.',
25
+ };
26
+ }
27
+
28
+ // Try to load onnxruntime-node. Returns { ok, error, info } instead of throwing.
29
+ export async function checkOnnxRuntime() {
30
+ const info = runtimeInfo();
31
+ if (!info.node) return { ok: true, info, nativeLoaded: false };
32
+ try {
33
+ const ort = await import('onnxruntime-node');
34
+ return { ok: true, info, nativeLoaded: true, versions: ort.env?.versions };
35
+ } catch (error) {
36
+ return {
37
+ ok: false,
38
+ info,
39
+ nativeLoaded: false,
40
+ error: error?.message ?? String(error),
41
+ suggestion: 'Use Node 20+ on a supported platform with a current Visual C++ runtime (Windows). If unavailable, run the model in a browser or use the Python package kecil_tts with onnxruntime.',
42
+ };
43
+ }
44
+ }
package/src/tts.js ADDED
@@ -0,0 +1,149 @@
1
+ // Malay text -> phonemes -> small ONNX model (transformers.js) -> 24 kHz audio.
2
+ // Adapted from https://huggingface.co/spaces/Suarify/kecil-tts-web/blob/main/kecil.js
3
+ //
4
+ // import { KecilTTS } from '@suarify/kecil-tts';
5
+ // const tts = await KecilTTS.load(); // WebGPU in browsers, CPU in Node
6
+ // const { audio, sampleRate } = await tts.speak('Selamat pagi, boleh saya bantu?');
7
+ //
8
+ // The graph has two inputs, input_ids (int64 [1,T]) and speed (float32 [1]); one voice, no style input.
9
+ import { normalize } from './g2p/ms_norm.js';
10
+ import { chunk } from './g2p/ms_g2p.js';
11
+ import { createG2P, G2P_OPTIONS } from './g2p/index.js';
12
+
13
+ export const SAMPLE_RATE = 24000;
14
+ export const DEFAULT_MODEL = 'Suarify/kecil-tts-yati-v0.5.0';
15
+ const MAX_PHONEMES = 400; // trained on single sentences of at most 400 phonemes
16
+ export const FIRST_MAX = 60; // streaming: first piece at most this many phonemes, sound starts early
17
+ export const LATER_MAX = 160; // streaming: every later piece at most this many phonemes
18
+ export { G2P_OPTIONS };
19
+
20
+ export function splitSentences(text) {
21
+ return text.split(/(?<=[.!?…])\s+|\n+/).map((s) => s.trim()).filter(Boolean);
22
+ }
23
+
24
+ // Loaded lazily so simply importing this package does not load the native
25
+ // onnxruntime-node binding on servers that cannot support it.
26
+ let TF;
27
+ async function loadTransformers() {
28
+ if (!TF) TF = await import('@huggingface/transformers');
29
+ return TF;
30
+ }
31
+
32
+ export class Suaradee {
33
+ constructor(model, g2p, device, tf) {
34
+ this.model = model;
35
+ this.g2p = g2p;
36
+ this.device = device;
37
+ this.tf = tf;
38
+ }
39
+
40
+ // model: Hugging Face repo id, or a folder name under modelRoot when local is true.
41
+ // device: 'auto' (WebGPU when the browser has it and it works, else WASM), 'webgpu', 'wasm' or 'cpu' (Node).
42
+ static async load({ model = DEFAULT_MODEL, g2p, dtype = 'q8', device = 'auto', local = false, modelRoot, sessionOptions, progressCallback } = {}) {
43
+ const inNode = typeof window === 'undefined';
44
+ const { StyleTextToSpeech2Model, Tensor, env } = await loadTransformers();
45
+ if (local) { env.allowLocalModels = true; env.allowRemoteModels = false; env.localModelPath = modelRoot; }
46
+ // Embedded pages (e.g. the Hugging Face Space iframe) are not cross-origin isolated, so
47
+ // SharedArrayBuffer is unavailable and ORT's threaded WASM cannot start. Single-threaded WASM
48
+ // needs no SAB and is the only backend an embed can use when WebGPU is denied.
49
+ if (!inNode && typeof self !== 'undefined' && !self.crossOriginIsolated && env.backends?.onnx?.wasm) {
50
+ env.backends.onnx.wasm.numThreads = 1;
51
+ }
52
+ // navigator.gpu can exist while the page is denied an adapter (embedded frames), so ask for one.
53
+ const webgpuOk = async () => {
54
+ if (inNode || typeof navigator === 'undefined' || !navigator.gpu) return false;
55
+ try { return !!(await navigator.gpu.requestAdapter()); } catch { return false; }
56
+ };
57
+ const tries = device !== 'auto' ? [device] : inNode ? ['cpu'] : ((await webgpuOk()) ? ['webgpu', 'wasm'] : ['wasm']);
58
+ const rules = g2p || createG2P(G2P_OPTIONS);
59
+ let lastErr;
60
+ for (const d of tries) {
61
+ try {
62
+ const options = { dtype, device: d, ...(sessionOptions ? { session_options: sessionOptions } : {}) };
63
+ if (progressCallback) options.progress_callback = progressCallback;
64
+ const m = await StyleTextToSpeech2Model.from_pretrained(model, options);
65
+ const inst = new Suaradee(m, rules, d, { Tensor });
66
+ await inst.synth(inst.phonemize('Selamat pagi.')[0]); // warm-up: surfaces unsupported operators now, not on first use
67
+ return inst;
68
+ } catch (e) { lastErr = e; console.warn(`KecilTTS: device ${d} failed`, e); }
69
+ }
70
+ throw lastErr;
71
+ }
72
+
73
+ // Alias matching the model repo examples.
74
+ static from_pretrained(model = DEFAULT_MODEL, options = {}) {
75
+ return this.load({ ...options, model });
76
+ }
77
+
78
+ phonemize(text) {
79
+ const out = [];
80
+ for (const sent of splitSentences(normalize(text))) {
81
+ const ph = this.g2p.phonemize(sent);
82
+ if (!/\p{L}/u.test(ph)) continue; // punctuation alone is not speech
83
+ out.push(...(ph.length <= MAX_PHONEMES ? [ph] : chunk(ph, MAX_PHONEMES)));
84
+ }
85
+ return out;
86
+ }
87
+
88
+ ids(phonemes) { return this.g2p.tokens(phonemes); }
89
+
90
+ async synth(phonemes, speed = 1.0) {
91
+ const { Tensor } = this.tf;
92
+ const ids = this.ids(phonemes);
93
+ const input_ids = new Tensor('int64', BigInt64Array.from(ids, (v) => BigInt(v)), [1, ids.length]);
94
+ const out = await this.model({ input_ids, speed: new Tensor('float32', new Float32Array([speed]), [1]) });
95
+ return out.waveform.data;
96
+ }
97
+
98
+ // Cut a phoneme string at commas only: first piece at most firstLimit symbols, later pieces at most
99
+ // laterLimit. A piece with no comma inside its limit is kept whole, so comma-free texts never change.
100
+ static splitCommas(phonemes, firstLimit, laterLimit) {
101
+ const out = [];
102
+ let rest = phonemes.trim();
103
+ let first = true;
104
+ for (;;) {
105
+ const limit = first ? firstLimit : laterLimit;
106
+ if (rest.length <= limit) { out.push(rest); return out; }
107
+ const cut = rest.lastIndexOf(',', limit);
108
+ if (cut < 0) { out.push(rest); return out; }
109
+ out.push(rest.slice(0, cut).trim());
110
+ rest = rest.slice(cut + 1).trim();
111
+ first = false;
112
+ if (!rest) return out;
113
+ }
114
+ }
115
+
116
+ // Phoneme pieces for streaming: sentences as phonemize() makes them, with pieces that exceed the
117
+ // streaming limit cut at commas.
118
+ pieces(text, firstMax = FIRST_MAX) {
119
+ const out = [];
120
+ for (const ph of this.phonemize(text)) out.push(...Suaradee.splitCommas(ph, firstMax, LATER_MAX));
121
+ return out;
122
+ }
123
+
124
+ // Yields one Float32Array per piece at SAMPLE_RATE; a pause-length gap between pieces. The consumer
125
+ // gets the first piece before the rest is synthesised.
126
+ async *stream(text, { speed = 1.0, pause = 0.12, firstMax = FIRST_MAX } = {}) {
127
+ const gap = new Float32Array(Math.round(pause * SAMPLE_RATE));
128
+ let emitted = false;
129
+ for (const p of this.pieces(text, firstMax)) {
130
+ if (!/\p{L}/u.test(p)) continue; // punctuation alone is not speech
131
+ if (emitted) yield gap.slice();
132
+ yield await this.synth(p, speed);
133
+ emitted = true;
134
+ }
135
+ }
136
+
137
+ async speak(text, opts = {}) {
138
+ const parts = [];
139
+ let total = 0;
140
+ for await (const y of this.stream(text, opts)) { parts.push(y); total += y.length; }
141
+ const audio = new Float32Array(total);
142
+ let o = 0;
143
+ for (const p of parts) { audio.set(p, o); o += p.length; }
144
+ return { audio, sampleRate: SAMPLE_RATE };
145
+ }
146
+ }
147
+
148
+ // Renamed alias (Suaradee kept for backwards compatibility).
149
+ export const KecilTTS = Suaradee;
package/src/wav.js ADDED
@@ -0,0 +1,46 @@
1
+ // Minimal mono 16-bit PCM WAV encoder. Works in browsers and Node.
2
+ // Returns an ArrayBuffer; wrap in a Blob for the browser or Buffer for Node.
3
+
4
+ function clamp16(x) {
5
+ const s = Math.max(-1, Math.min(1, x));
6
+ return s < 0 ? Math.round(s * 0x8000) : Math.round(s * 0x7fff);
7
+ }
8
+
9
+ export function encodeWav(samples, sampleRate = 24000) {
10
+ const n = samples.length;
11
+ const buffer = new ArrayBuffer(44 + n * 2);
12
+ const view = new DataView(buffer);
13
+
14
+ const ascii = (offset, text) => {
15
+ for (let i = 0; i < text.length; i++) view.setUint8(offset + i, text.charCodeAt(i));
16
+ };
17
+
18
+ ascii(0, 'RIFF');
19
+ view.setUint32(4, 36 + n * 2, true);
20
+ ascii(8, 'WAVE');
21
+ ascii(12, 'fmt ');
22
+ view.setUint32(16, 16, true); // PCM chunk size
23
+ view.setUint16(20, 1, true); // PCM format
24
+ view.setUint16(22, 1, true); // mono
25
+ view.setUint32(24, sampleRate, true);
26
+ view.setUint32(28, sampleRate * 2, true);
27
+ view.setUint16(32, 2, true); // block align
28
+ view.setUint16(34, 16, true); // bits per sample
29
+ ascii(36, 'data');
30
+ view.setUint32(40, n * 2, true);
31
+
32
+ for (let i = 0; i < n; i++) view.setInt16(44 + i * 2, clamp16(samples[i]), true);
33
+ return buffer;
34
+ }
35
+
36
+ export function concatFloat32(chunks) {
37
+ let total = 0;
38
+ for (const c of chunks) total += c.length;
39
+ const out = new Float32Array(total);
40
+ let offset = 0;
41
+ for (const c of chunks) {
42
+ out.set(c, offset);
43
+ offset += c.length;
44
+ }
45
+ return out;
46
+ }