1 +// noko-parakeet.mjs — Parakeet ONNX model-directory runtime.
3 +import { createRequire } from 'node:module';
4 +import { existsSync, readFileSync, readdirSync } from 'node:fs';
5 +import { join } from 'node:path';
6 +import { loadOnnxRuntime } from './noko-vad.mjs';
8 +const require = createRequire(import.meta.url);
9 +const DEFAULT_MAX_TOKENS_PER_STEP = 10;
11 +export function loadSentencePiece() {
13 + return require('sentencepiece-js');
15 + throw new Error(`tokenizer runtime unavailable: sentencepiece-js (${error.message})`);
19 +function walk(dir, prefix = '') {
20 + if (!dir || !existsSync(dir)) return [];
22 + for (const entry of readdirSync(dir, { withFileTypes: true })) {
23 + if (entry.name.startsWith('._')) continue;
24 + const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
25 + const abs = join(dir, entry.name);
26 + if (entry.isDirectory()) out.push(...walk(abs, rel));
27 + else out.push({ rel, abs });
32 +function pick(files, tests) {
33 + return files.find(file => tests.some(test => test.test(file.rel.toLowerCase()))) || null;
36 +export function discoverParakeetDir(dir) {
37 + const files = walk(dir);
39 + preprocessor: pick(files, [/preprocessor.*\.onnx$/, /nemo\d+.*\.onnx$/]),
40 + encoder: pick(files, [/encoder.*\.onnx$/]),
41 + decoderJoint: pick(files, [/(decoder|joint).*\.onnx$/]),
42 + tokenizer: pick(files, [/tokenizer\.model$/, /vocab.*\.(txt|json)$/])
45 + if (!found.preprocessor) missing.push('preprocessor');
46 + if (!found.encoder) missing.push('encoder');
47 + if (!found.decoderJoint) missing.push('decoder-or-joint');
48 + if (!found.tokenizer) missing.push('vocabulary-or-tokenizer');
51 + ok: missing.length === 0,
53 + files: Object.fromEntries(Object.entries(found).map(([key, value]) => [key, value ? value.rel : '']))
57 +export async function loadTokenizer(path, runtime) {
58 + const sp = runtime || loadSentencePiece();
59 + const processor = new sp.SentencePieceProcessor();
60 + await processor.load(path);
64 +export function decodeTokens(tokenizer, tokens) {
65 + if (!tokenizer || typeof tokenizer.decodeIds !== 'function') throw new Error('sentencepiece tokenizer missing');
66 + return tokenizer.decodeIds((tokens || []).map(Number));
69 +function loadVocabulary(path) {
70 + const vocab = new Map();
71 + for (const line of readFileSync(path, 'utf8').split(/\r?\n/)) {
72 + if (!line) continue;
73 + const split = line.lastIndexOf(' ');
74 + if (split <= 0) continue;
75 + vocab.set(Number(line.slice(split + 1)), line.slice(0, split).replaceAll('▁', ' '));
77 + const blank = Array.from(vocab.entries()).find(([, token]) => token === '<blk>');
82 + blankIdx: blank ? blank[0] : Math.max(...vocab.keys()),
84 + const text = ids.map(id => vocab.get(id) || '').join('');
85 + return text.replace(/^\s|\s\B|(\s)\b/g, (_match, keep) => keep ? ' ' : '');
90 +async function loadDecoder(path, options) {
91 + if (path.toLowerCase().endsWith('.model')) {
92 + const tokenizer = await loadTokenizer(path, options.sentencepiece);
94 + type: 'sentencepiece',
97 + decodeIds: ids => decodeTokens(tokenizer, ids)
100 + return loadVocabulary(path);
103 +function first(record, names) {
104 + for (const name of names) if (record[name] !== undefined) return record[name];
105 + return Object.values(record)[0];
108 +function tensorData(tensor) {
109 + return tensor && tensor.data !== undefined ? tensor.data : tensor;
112 +function numericDim(value, fallback) {
113 + return typeof value === 'number' && value > 0 ? value : fallback;
116 +function argmax(data, start = 0, end = data.length) {
118 + for (let i = start + 1; i < end; i++) if (data[i] > data[best]) best = i;
119 + return best - start;
122 +export class ParakeetOnnx {
123 + constructor(ort, sessions, model, decoder, options = {}) {
125 + this.sessions = sessions;
126 + this.model = model;
127 + this.decoder = decoder;
128 + this.maxTokensPerStep = Number(options.maxTokensPerStep || DEFAULT_MAX_TOKENS_PER_STEP);
130 + this.state = 'ready';
133 + static async create(dir, options = {}) {
134 + const model = discoverParakeetDir(dir);
135 + if (!model.ok) throw new Error(`parakeet model dir incomplete: ${model.missing.join(', ')}`);
136 + const ort = options.ort || await loadOnnxRuntime();
137 + const sessionOptions = { executionProviders: options.executionProviders || ['cpu'] };
139 + preprocessor: await ort.InferenceSession.create(join(dir, model.files.preprocessor), sessionOptions),
140 + encoder: await ort.InferenceSession.create(join(dir, model.files.encoder), sessionOptions),
141 + decoderJoint: await ort.InferenceSession.create(join(dir, model.files.decoderJoint), sessionOptions)
143 + const decoder = await loadDecoder(join(dir, model.files.tokenizer), options);
144 + return new ParakeetOnnx(ort, sessions, model, decoder, options);
147 + async preprocess(samples) {
148 + const output = await this.sessions.preprocessor.run({
149 + waveforms: new this.ort.Tensor('float32', samples, [1, samples.length]),
150 + waveforms_lens: new this.ort.Tensor('int64', BigInt64Array.from([BigInt(samples.length)]), [1])
153 + features: first(output, ['features']),
154 + lengths: first(output, ['features_lens'])
158 + async encode(features, lengths) {
159 + const output = await this.sessions.encoder.run({
160 + audio_signal: features,
164 + encoded: first(output, ['outputs']),
165 + lengths: first(output, ['encoded_lengths'])
169 + createDecoderState() {
170 + const inputs = Object.fromEntries((this.sessions.decoderJoint.inputNames || []).map(name => [name, null]));
171 + const metadata = Object.fromEntries((this.sessions.decoderJoint.inputMetadata || []).map(input => [input.name, input]));
172 + const shape1 = metadata.input_states_1 ? metadata.input_states_1.shape : [2, 1, 640];
173 + const shape2 = metadata.input_states_2 ? metadata.input_states_2.shape : [2, 1, 640];
176 + state1: new Float32Array(numericDim(shape1[0], 2) * 1 * numericDim(shape1[2], 640)),
177 + state2: new Float32Array(numericDim(shape2[0], 2) * 1 * numericDim(shape2[2], 640)),
178 + state1Shape: [numericDim(shape1[0], 2), 1, numericDim(shape1[2], 640)],
179 + state2Shape: [numericDim(shape2[0], 2), 1, numericDim(shape2[2], 640)]
183 + async decodeFrame(prevTokens, state, frame) {
184 + const previous = prevTokens.length ? prevTokens[prevTokens.length - 1] : this.decoder.blankIdx;
185 + const output = await this.sessions.decoderJoint.run({
186 + encoder_outputs: new this.ort.Tensor('float32', frame, [1, frame.length, 1]),
187 + targets: new this.ort.Tensor('int32', Int32Array.from([previous]), [1, 1]),
188 + target_length: new this.ort.Tensor('int32', Int32Array.from([1]), [1]),
189 + input_states_1: new this.ort.Tensor('float32', state.state1, state.state1Shape),
190 + input_states_2: new this.ort.Tensor('float32', state.state2, state.state2Shape)
192 + const logits = tensorData(first(output, ['outputs']));
195 + step: argmax(logits, this.decoder.size, logits.length),
197 + state1: new Float32Array(tensorData(first(output, ['output_states_1']))),
198 + state2: new Float32Array(tensorData(first(output, ['output_states_2']))),
199 + state1Shape: state.state1Shape,
200 + state2Shape: state.state2Shape
205 + async transcribe(samples) {
206 + if (this.busy) throw new Error('parakeet inference already running');
207 + if (!samples || samples.length === 0) throw new Error('empty speech buffer');
209 + this.state = 'transcribing';
211 + const { features, lengths } = await this.preprocess(samples instanceof Float32Array ? samples : new Float32Array(samples));
212 + const { encoded, lengths: encodedLengths } = await this.encode(features, lengths);
213 + const encodedData = tensorData(encoded);
214 + const dims = encoded.dims || encoded.dimensions;
215 + const channels = Number(dims[1]);
216 + const frames = Number(dims[2]);
217 + const limit = Math.min(frames, Number(tensorData(encodedLengths)[0]));
218 + const state = this.createDecoderState();
219 + let currentState = state;
221 + let emittedTokens = 0;
222 + for (let t = 0; t < limit;) {
223 + const frame = new Float32Array(channels);
224 + for (let c = 0; c < channels; c++) frame[c] = encodedData[c * frames + t];
225 + const decoded = await this.decodeFrame(tokens, currentState, frame);
226 + const token = argmax(decoded.logits, 0, this.decoder.size);
227 + if (token !== this.decoder.blankIdx) {
228 + currentState = decoded.state;
229 + tokens.push(token);
232 + if (decoded.step > 0) {
235 + } else if (token === this.decoder.blankIdx || emittedTokens === this.maxTokensPerStep) {
241 + text: this.decoder.decodeIds(tokens),
243 + model: 'parakeet-onnx',
244 + quantization: this.model.files.encoder.includes('int8') ? 'int8' : 'unknown',
245 + runtimeProvider: 'onnxruntime-node'
250 + this.state = 'ready';