@basecompute/basert 0.0.0-stage → 0.4.2
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 +202 -0
- package/NOTICE +15 -0
- package/README.md +40 -2
- package/bin/basert.js +75 -0
- package/dist/index.d.ts +210 -0
- package/dist/index.js +823 -0
- package/package.json +46 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,823 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* @baseRT/node — Node.js / TypeScript bindings for the BaseRT LLM inference
|
|
4
|
+
* engine (Apple Silicon / Metal).
|
|
5
|
+
*
|
|
6
|
+
* Implemented on top of koffi (https://koffi.dev) — a maintained, prebuilt FFI
|
|
7
|
+
* for Node that needs no node-gyp / native addon compilation and correctly
|
|
8
|
+
* handles struct-by-value arguments/returns and C callbacks on Node 18–22.
|
|
9
|
+
*
|
|
10
|
+
* import { BaseRTModel } from "@baseRT/node";
|
|
11
|
+
* const model = new BaseRTModel("model.base");
|
|
12
|
+
* const text = model.generateText(model.encode("Hello, world!"), 128);
|
|
13
|
+
* model.close();
|
|
14
|
+
*
|
|
15
|
+
* Generation calls are synchronous and block the calling thread for their
|
|
16
|
+
* duration (local inference is CPU/GPU-bound); run them in a worker_thread if
|
|
17
|
+
* you need the event loop free. The streaming `onToken` callback is invoked
|
|
18
|
+
* synchronously per token from inside the call.
|
|
19
|
+
*/
|
|
20
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
21
|
+
if (k2 === undefined) k2 = k;
|
|
22
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
23
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
24
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
25
|
+
}
|
|
26
|
+
Object.defineProperty(o, k2, desc);
|
|
27
|
+
}) : (function(o, m, k, k2) {
|
|
28
|
+
if (k2 === undefined) k2 = k;
|
|
29
|
+
o[k2] = m[k];
|
|
30
|
+
}));
|
|
31
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
32
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
33
|
+
}) : function(o, v) {
|
|
34
|
+
o["default"] = v;
|
|
35
|
+
});
|
|
36
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
37
|
+
var ownKeys = function(o) {
|
|
38
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
39
|
+
var ar = [];
|
|
40
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
41
|
+
return ar;
|
|
42
|
+
};
|
|
43
|
+
return ownKeys(o);
|
|
44
|
+
};
|
|
45
|
+
return function (mod) {
|
|
46
|
+
if (mod && mod.__esModule) return mod;
|
|
47
|
+
var result = {};
|
|
48
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
49
|
+
__setModuleDefault(result, mod);
|
|
50
|
+
return result;
|
|
51
|
+
};
|
|
52
|
+
})();
|
|
53
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
54
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
55
|
+
};
|
|
56
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
57
|
+
exports.__internal = exports.BaseRTModel = exports.Engine = void 0;
|
|
58
|
+
const koffi_1 = __importDefault(require("koffi"));
|
|
59
|
+
const fs = __importStar(require("fs"));
|
|
60
|
+
const os = __importStar(require("os"));
|
|
61
|
+
const path = __importStar(require("path"));
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
// Library resolution
|
|
64
|
+
// ---------------------------------------------------------------------------
|
|
65
|
+
// Platform-appropriate shared-library filenames, most likely first. Metal/
|
|
66
|
+
// macOS is the only shipping backend today, but selecting by platform means
|
|
67
|
+
// this loader needs no change when a Linux (CUDA/ROCm) or Windows build appears
|
|
68
|
+
// — the C ABI is identical, only the file name differs.
|
|
69
|
+
function libNames() {
|
|
70
|
+
switch (process.platform) {
|
|
71
|
+
case "darwin":
|
|
72
|
+
return ["libbaseRT.dylib"];
|
|
73
|
+
case "win32":
|
|
74
|
+
return ["baseRT.dll", "libbaseRT.dll"];
|
|
75
|
+
default:
|
|
76
|
+
return ["libbaseRT.so"]; // linux / other unix
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
// The prebuilt engine is published to npm as one package per platform, listed
|
|
80
|
+
// as optionalDependencies of @basecompute/basert; npm installs only the one
|
|
81
|
+
// whose os/cpu match this machine.
|
|
82
|
+
const ENGINE_PACKAGES = {
|
|
83
|
+
"darwin-arm64": "@basecompute/basert-darwin-arm64",
|
|
84
|
+
"linux-arm64": "@basecompute/basert-linux-arm64-cuda",
|
|
85
|
+
};
|
|
86
|
+
function enginePackageDir() {
|
|
87
|
+
const pkg = ENGINE_PACKAGES[`${process.platform}-${process.arch}`];
|
|
88
|
+
if (!pkg)
|
|
89
|
+
return undefined;
|
|
90
|
+
try {
|
|
91
|
+
return path.join(path.dirname(require.resolve(`${pkg}/package.json`)), "engine");
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return undefined; // not installed: a source checkout, or --no-optional
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function resolveLibPath() {
|
|
98
|
+
if (process.env.BASERT_LIB_PATH)
|
|
99
|
+
return process.env.BASERT_LIB_PATH;
|
|
100
|
+
const here = __dirname; // dist/ or src/ at runtime
|
|
101
|
+
// A source checkout's build directory comes before the installed engines
|
|
102
|
+
// (install.sh / Homebrew) so a fresh local build is never shadowed by an
|
|
103
|
+
// older release. The working directory is tried last: whatever folder the
|
|
104
|
+
// script runs in must never outrank an installed engine, or a project could
|
|
105
|
+
// ship its own library.
|
|
106
|
+
const installDir = process.env.BASERT_INSTALL_DIR || path.join(os.homedir(), ".basert");
|
|
107
|
+
const dirs = [
|
|
108
|
+
enginePackageDir(), // npm install @basecompute/basert
|
|
109
|
+
path.resolve(here, "..", "..", "..", "build"), // bindings/node/{dist,src} -> repo/build
|
|
110
|
+
path.resolve(here, "..", "..", "build"),
|
|
111
|
+
installDir, // install.sh
|
|
112
|
+
"/opt/homebrew/opt/basert/libexec", // brew, macOS
|
|
113
|
+
"/home/linuxbrew/.linuxbrew/opt/basert/libexec", // brew, Linux
|
|
114
|
+
path.resolve(process.cwd(), "build"),
|
|
115
|
+
path.resolve(process.cwd()),
|
|
116
|
+
].filter((d) => d !== undefined);
|
|
117
|
+
const names = libNames();
|
|
118
|
+
const tried = [];
|
|
119
|
+
for (const d of dirs) {
|
|
120
|
+
for (const name of names) {
|
|
121
|
+
const c = path.join(d, name);
|
|
122
|
+
tried.push(c);
|
|
123
|
+
if (fs.existsSync(c))
|
|
124
|
+
return c;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
throw new Error(`Cannot find ${names.join(" / ")}. Install the engine (npm install @basecompute/basert, brew install basecompute/tap/basert, or install.sh), set BASERT_LIB_PATH, or build with \`make shared\`. Looked in:\n ${tried.join("\n ")}`);
|
|
128
|
+
}
|
|
129
|
+
// ---------------------------------------------------------------------------
|
|
130
|
+
// C struct definitions (koffi computes offsets/size from the field list, so
|
|
131
|
+
// these track include/baseRT/types.h exactly — including the fields the old
|
|
132
|
+
// hand-written offset table dropped, e.g. `sliding_window`).
|
|
133
|
+
// ---------------------------------------------------------------------------
|
|
134
|
+
const ModelConfigC = koffi_1.default.struct("BaseRTModelConfig", {
|
|
135
|
+
dim: "uint32",
|
|
136
|
+
n_layers: "uint32",
|
|
137
|
+
n_heads: "uint32",
|
|
138
|
+
n_kv_heads: "uint32",
|
|
139
|
+
head_dim: "uint32",
|
|
140
|
+
q_dim: "uint32",
|
|
141
|
+
kv_dim: "uint32",
|
|
142
|
+
ffn_dim: "uint32",
|
|
143
|
+
vocab_size: "uint32",
|
|
144
|
+
max_seq_len: "uint32",
|
|
145
|
+
norm_eps: "float",
|
|
146
|
+
rope_theta: "float",
|
|
147
|
+
sliding_window_pattern: "uint32",
|
|
148
|
+
sliding_window: "uint32",
|
|
149
|
+
rope_local_theta: "float",
|
|
150
|
+
architecture: koffi_1.default.array("char", 32),
|
|
151
|
+
// Encoder (Whisper)
|
|
152
|
+
enc_n_layers: "uint32",
|
|
153
|
+
enc_n_heads: "uint32",
|
|
154
|
+
enc_dim: "uint32",
|
|
155
|
+
enc_ffn_dim: "uint32",
|
|
156
|
+
n_mels: "uint32",
|
|
157
|
+
enc_max_seq_len: "uint32",
|
|
158
|
+
// Gemma 4
|
|
159
|
+
n_embd_per_layer: "uint32",
|
|
160
|
+
n_layer_kv_from_start: "uint32",
|
|
161
|
+
logit_softcap: "float",
|
|
162
|
+
attention_scale: "float",
|
|
163
|
+
head_dim_swa: "uint32",
|
|
164
|
+
head_dim_global: "uint32",
|
|
165
|
+
global_rope_partial_factor: "float",
|
|
166
|
+
swa_layers: koffi_1.default.array("uint8", 64),
|
|
167
|
+
ffn_dims: koffi_1.default.array("uint32", 128),
|
|
168
|
+
n_kv_heads_per_layer: koffi_1.default.array("uint32", 128),
|
|
169
|
+
// Qwen3.5 / 3.6 hybrid linear-attention (Gated DeltaNet)
|
|
170
|
+
attn_output_gate: "uint8",
|
|
171
|
+
_qwen35_pad: koffi_1.default.array("uint8", 3),
|
|
172
|
+
partial_rotary_factor: "float",
|
|
173
|
+
full_attention_interval: "uint32",
|
|
174
|
+
linear_attn_layers: koffi_1.default.array("uint8", 64),
|
|
175
|
+
gdn_num_k_heads: "uint32",
|
|
176
|
+
gdn_num_v_heads: "uint32",
|
|
177
|
+
gdn_key_head_dim: "uint32",
|
|
178
|
+
gdn_value_head_dim: "uint32",
|
|
179
|
+
gdn_conv_kernel: "uint32",
|
|
180
|
+
// Nemotron-H hybrid Mamba-2 SSM
|
|
181
|
+
ssm_state_size: "uint32",
|
|
182
|
+
ssm_conv_kernel: "uint32",
|
|
183
|
+
ssm_num_groups: "uint32",
|
|
184
|
+
ssm_inner_size: "uint32",
|
|
185
|
+
ssm_num_heads: "uint32",
|
|
186
|
+
// MoE
|
|
187
|
+
n_experts: "uint32",
|
|
188
|
+
n_experts_used: "uint32",
|
|
189
|
+
n_experts_shared: "uint32",
|
|
190
|
+
expert_ffn_dim: "uint32",
|
|
191
|
+
expert_gating: "uint8",
|
|
192
|
+
norm_topk_prob: "uint8",
|
|
193
|
+
_moe_pad: koffi_1.default.array("uint8", 2),
|
|
194
|
+
expert_weights_scale: "float",
|
|
195
|
+
// Vision tower
|
|
196
|
+
vision_n_layers: "uint32",
|
|
197
|
+
vision_dim: "uint32",
|
|
198
|
+
vision_n_heads: "uint32",
|
|
199
|
+
vision_head_dim: "uint32",
|
|
200
|
+
vision_ffn_dim: "uint32",
|
|
201
|
+
vision_patch_size: "uint32",
|
|
202
|
+
vision_image_size: "uint32",
|
|
203
|
+
vision_pooling_kernel: "uint32",
|
|
204
|
+
vision_soft_tokens: "uint32",
|
|
205
|
+
vision_norm_eps: "float",
|
|
206
|
+
vision_rope_theta: "float",
|
|
207
|
+
vision_pos_embed_size: "uint32",
|
|
208
|
+
image_token_id: "uint32",
|
|
209
|
+
boi_token_id: "uint32",
|
|
210
|
+
eoi_token_id: "uint32",
|
|
211
|
+
// Vision-tower family selector + Qwen3-VL-style extras
|
|
212
|
+
vision_arch: "uint32",
|
|
213
|
+
vision_spatial_merge: "uint32",
|
|
214
|
+
vision_temporal_patch: "uint32",
|
|
215
|
+
vision_out_dim: "uint32",
|
|
216
|
+
// Audio tower
|
|
217
|
+
audio_n_layers: "uint32",
|
|
218
|
+
audio_dim: "uint32",
|
|
219
|
+
audio_n_heads: "uint32",
|
|
220
|
+
audio_head_dim: "uint32",
|
|
221
|
+
audio_ffn_dim: "uint32",
|
|
222
|
+
audio_output_proj_dim: "uint32",
|
|
223
|
+
audio_chunk_size: "uint32",
|
|
224
|
+
audio_left_context: "uint32",
|
|
225
|
+
audio_conv_kernel: "uint32",
|
|
226
|
+
audio_soft_tokens: "uint32",
|
|
227
|
+
audio_logit_softcap: "float",
|
|
228
|
+
audio_norm_eps: "float",
|
|
229
|
+
audio_gradient_clip: "float",
|
|
230
|
+
audio_residual_weight: "float",
|
|
231
|
+
audio_ms_per_token: "float",
|
|
232
|
+
audio_sscp_channels: koffi_1.default.array("uint32", 2),
|
|
233
|
+
audio_token_id: "uint32",
|
|
234
|
+
boa_token_id: "uint32",
|
|
235
|
+
eoa_token_id: "uint32",
|
|
236
|
+
mrope_section: koffi_1.default.array("uint32", 3),
|
|
237
|
+
mrope_interleaved: "uint8",
|
|
238
|
+
_mrope_pad: koffi_1.default.array("uint8", 3),
|
|
239
|
+
rope_scaling_factor: "float",
|
|
240
|
+
rope_low_freq_factor: "float",
|
|
241
|
+
rope_high_freq_factor: "float",
|
|
242
|
+
rope_orig_max_pos: "uint32",
|
|
243
|
+
rope_scaling_type: "uint32",
|
|
244
|
+
// Muse Glimmer (0 / empty = not applicable)
|
|
245
|
+
qk_scale_factor: "float",
|
|
246
|
+
output_multiplier: "float",
|
|
247
|
+
post_norm_eps: "float",
|
|
248
|
+
nope_layers: koffi_1.default.array("uint8", 64),
|
|
249
|
+
embed_norm_eps: "float",
|
|
250
|
+
vision_window_layers: koffi_1.default.array("uint8", 64),
|
|
251
|
+
vision_window_size: "uint32",
|
|
252
|
+
vision_pos_embed_h: "uint32",
|
|
253
|
+
vision_pos_embed_w: "uint32",
|
|
254
|
+
vision_adapter_dim: "uint32",
|
|
255
|
+
video_token_id: "uint32",
|
|
256
|
+
// GLM 5.2 / glm-dsa
|
|
257
|
+
q_lora_rank: "uint32",
|
|
258
|
+
kv_lora_rank: "uint32",
|
|
259
|
+
qk_nope_head_dim: "uint32",
|
|
260
|
+
qk_rope_head_dim: "uint32",
|
|
261
|
+
v_head_dim: "uint32",
|
|
262
|
+
routed_scaling_factor: "float",
|
|
263
|
+
first_k_dense_replace: "uint32",
|
|
264
|
+
nextn_predict_layers: "uint32",
|
|
265
|
+
indexer_head_count: "uint32",
|
|
266
|
+
indexer_key_length: "uint32",
|
|
267
|
+
indexer_top_k: "uint32",
|
|
268
|
+
// gpt-oss
|
|
269
|
+
rope_yarn_beta_fast: "float",
|
|
270
|
+
rope_yarn_beta_slow: "float",
|
|
271
|
+
swiglu_limit: "float",
|
|
272
|
+
swiglu_alpha: "float",
|
|
273
|
+
attention_sinks: "uint8",
|
|
274
|
+
attention_bias: "uint8",
|
|
275
|
+
rope_yarn_truncate: "uint8",
|
|
276
|
+
_gptoss_pad: "uint8",
|
|
277
|
+
});
|
|
278
|
+
const SamplingConfigC = koffi_1.default.struct("BaseRTSamplingConfig", {
|
|
279
|
+
temperature: "float",
|
|
280
|
+
top_k: "int",
|
|
281
|
+
top_p: "float",
|
|
282
|
+
min_p: "float",
|
|
283
|
+
repeat_penalty: "float",
|
|
284
|
+
presence_penalty: "float",
|
|
285
|
+
frequency_penalty: "float",
|
|
286
|
+
seed: "uint32",
|
|
287
|
+
n_logit_bias: "int32",
|
|
288
|
+
logit_bias_tokens: "int32 *",
|
|
289
|
+
logit_bias_values: "float *",
|
|
290
|
+
});
|
|
291
|
+
const GenerationStatsC = koffi_1.default.struct("BaseRTGenerationStats", {
|
|
292
|
+
prompt_tokens: "int",
|
|
293
|
+
generated_tokens: "int",
|
|
294
|
+
prefill_time_ms: "float",
|
|
295
|
+
decode_time_ms: "float",
|
|
296
|
+
prefill_tokens_per_sec: "float",
|
|
297
|
+
decode_tokens_per_sec: "float",
|
|
298
|
+
});
|
|
299
|
+
const TranscribeStatsC = koffi_1.default.struct("BaseRTTranscribeStats", {
|
|
300
|
+
n_tokens: "int",
|
|
301
|
+
audio_ms: "float",
|
|
302
|
+
encode_ms: "float",
|
|
303
|
+
decode_ms: "float",
|
|
304
|
+
total_ms: "float",
|
|
305
|
+
});
|
|
306
|
+
const TranscribeSegmentC = koffi_1.default.struct("BaseRTTranscribeSegment", {
|
|
307
|
+
start_ms: "int",
|
|
308
|
+
end_ms: "int",
|
|
309
|
+
text: "const char *",
|
|
310
|
+
avg_logprob: "float",
|
|
311
|
+
no_speech_prob: "float",
|
|
312
|
+
compression_ratio: "float",
|
|
313
|
+
temperature: "float",
|
|
314
|
+
});
|
|
315
|
+
// bool (*)(uint32_t token_id, const char *text, void *user_data)
|
|
316
|
+
const TokenCallbackC = koffi_1.default.proto("bool TokenCallback(uint32_t token_id, const char *text, void *user_data)");
|
|
317
|
+
// bool (*)(int start_ms, int end_ms, const char *text, void *user_data)
|
|
318
|
+
const SegmentCallbackC = koffi_1.default.proto("bool SegmentCallback(int start_ms, int end_ms, const char *text, void *user_data)");
|
|
319
|
+
let _lib = null;
|
|
320
|
+
function lib() {
|
|
321
|
+
if (_lib)
|
|
322
|
+
return _lib;
|
|
323
|
+
const k = koffi_1.default.load(resolveLibPath());
|
|
324
|
+
const out = "_Out_";
|
|
325
|
+
void out;
|
|
326
|
+
_lib = {
|
|
327
|
+
baseRT_version_string: k.func("const char *baseRT_version_string()"),
|
|
328
|
+
baseRT_load_model: k.func("void *baseRT_load_model(const char *, const char *, int)"),
|
|
329
|
+
baseRT_free_model: k.func("void baseRT_free_model(void *)"),
|
|
330
|
+
baseRT_get_config: k.func("BaseRTModelConfig baseRT_get_config(void *)"),
|
|
331
|
+
baseRT_model_memory: k.func("size_t baseRT_model_memory(void *)"),
|
|
332
|
+
baseRT_get_error: k.func("const char *baseRT_get_error()"),
|
|
333
|
+
baseRT_set_kv_bits: k.func("void baseRT_set_kv_bits(int)"),
|
|
334
|
+
baseRT_set_paged_kv: k.func("void baseRT_set_paged_kv(int)"),
|
|
335
|
+
baseRT_set_max_batch_size: k.func("void baseRT_set_max_batch_size(int)"),
|
|
336
|
+
baseRT_set_prefill_chunk: k.func("void baseRT_set_prefill_chunk(int)"),
|
|
337
|
+
baseRT_set_paged_weights: k.func("void baseRT_set_paged_weights(int)"),
|
|
338
|
+
baseRT_set_baked_decode: k.func("void baseRT_set_baked_decode(int)"),
|
|
339
|
+
baseRT_set_gpu_wait_timeout_ms: k.func("void baseRT_set_gpu_wait_timeout_ms(double)"),
|
|
340
|
+
baseRT_encode: k.func("int baseRT_encode(void *, const char *, _Out_ uint32_t *, int)"),
|
|
341
|
+
baseRT_token_count: k.func("int baseRT_token_count(void *, const char *)"),
|
|
342
|
+
baseRT_decode_token: k.func("const char *baseRT_decode_token(void *, uint32_t)"),
|
|
343
|
+
baseRT_decode_token_static: k.func("const char *baseRT_decode_token_static(void *, uint32_t)"),
|
|
344
|
+
baseRT_generate: k.func("BaseRTGenerationStats baseRT_generate(void *, uint32_t *, int, int, BaseRTSamplingConfig, TokenCallback *, void *)"),
|
|
345
|
+
baseRT_generate_continue: k.func("BaseRTGenerationStats baseRT_generate_continue(void *, uint32_t *, int, int, BaseRTSamplingConfig, TokenCallback *, void *)"),
|
|
346
|
+
baseRT_prefill: k.func("uint32_t baseRT_prefill(void *, uint32_t *, int)"),
|
|
347
|
+
baseRT_prefill_image: k.func("uint32_t baseRT_prefill_image(void *, uint32_t *, int, const char *)"),
|
|
348
|
+
baseRT_image_num_tokens: k.func("int baseRT_image_num_tokens(void *, const char *)"),
|
|
349
|
+
baseRT_prefill_audio: k.func("uint32_t baseRT_prefill_audio(void *, uint32_t *, int, float *, int)"),
|
|
350
|
+
baseRT_audio_num_tokens: k.func("int baseRT_audio_num_tokens(void *, int)"),
|
|
351
|
+
baseRT_decode_step: k.func("uint32_t baseRT_decode_step(void *, uint32_t, int)"),
|
|
352
|
+
baseRT_chain_decode: k.func("int baseRT_chain_decode(void *, uint32_t, int, int, _Out_ uint32_t *)"),
|
|
353
|
+
baseRT_get_position: k.func("int baseRT_get_position(void *)"),
|
|
354
|
+
baseRT_set_speculation: k.func("void baseRT_set_speculation(void *, bool)"),
|
|
355
|
+
baseRT_reset: k.func("void baseRT_reset(void *)"),
|
|
356
|
+
baseRT_embed: k.func("int baseRT_embed(void *, uint32_t *, int, _Out_ float *, int)"),
|
|
357
|
+
baseRT_embed_text: k.func("int baseRT_embed_text(void *, const char *, _Out_ float *, int)"),
|
|
358
|
+
baseRT_embedding_dim: k.func("int baseRT_embedding_dim(void *)"),
|
|
359
|
+
baseRT_format_chat: k.func("const char *baseRT_format_chat(void *, const char *, const char *)"),
|
|
360
|
+
baseRT_chat_template: k.func("const char *baseRT_chat_template(void *)"),
|
|
361
|
+
baseRT_is_whisper: k.func("bool baseRT_is_whisper(void *)"),
|
|
362
|
+
baseRT_set_timestamps: k.func("void baseRT_set_timestamps(void *, bool)"),
|
|
363
|
+
baseRT_set_task: k.func("bool baseRT_set_task(void *, const char *)"),
|
|
364
|
+
baseRT_set_initial_prompt: k.func("void baseRT_set_initial_prompt(void *, const char *)"),
|
|
365
|
+
baseRT_set_condition_on_previous_text: k.func("void baseRT_set_condition_on_previous_text(void *, bool)"),
|
|
366
|
+
baseRT_transcribe_language: k.func("const char *baseRT_transcribe_language(void *)"),
|
|
367
|
+
baseRT_transcribe_audio_duration_ms: k.func("int baseRT_transcribe_audio_duration_ms(void *)"),
|
|
368
|
+
baseRT_transcribe_segment_count: k.func("int baseRT_transcribe_segment_count(void *)"),
|
|
369
|
+
baseRT_transcribe_segment: k.func("bool baseRT_transcribe_segment(void *, int, _Out_ BaseRTTranscribeSegment *)"),
|
|
370
|
+
baseRT_transcribe: k.func("const char *baseRT_transcribe(void *, const char *, const char *, _Out_ BaseRTTranscribeStats *)"),
|
|
371
|
+
baseRT_transcribe_pcm: k.func("const char *baseRT_transcribe_pcm(void *, float *, int, const char *, _Out_ BaseRTTranscribeStats *)"),
|
|
372
|
+
baseRT_transcribe_stream: k.func("const char *baseRT_transcribe_stream(void *, const char *, const char *, _Out_ BaseRTTranscribeStats *, SegmentCallback *, void *)"),
|
|
373
|
+
baseRT_transcribe_pcm_stream: k.func("const char *baseRT_transcribe_pcm_stream(void *, float *, int, const char *, _Out_ BaseRTTranscribeStats *, SegmentCallback *, void *)"),
|
|
374
|
+
};
|
|
375
|
+
// ModelConfigC is mirrored by hand above; a size mismatch means the mirror
|
|
376
|
+
// drifted from include/baseRT/types.h and every field after the divergence
|
|
377
|
+
// point decodes as garbage. Fail at load, not at use. (Older libraries
|
|
378
|
+
// predate the symbol; skip the check there.)
|
|
379
|
+
try {
|
|
380
|
+
const configSizeof = k.func("size_t baseRT_model_config_sizeof()");
|
|
381
|
+
const cSize = Number(configSizeof());
|
|
382
|
+
const jsSize = koffi_1.default.sizeof(ModelConfigC);
|
|
383
|
+
if (cSize !== jsSize) {
|
|
384
|
+
throw new Error(`BaseRTModelConfig layout drift: library says ${cSize} bytes, ` +
|
|
385
|
+
`Node mirror is ${jsSize} bytes. Update ModelConfigC in ` +
|
|
386
|
+
`bindings/node/src/index.ts to match include/baseRT/types.h.`);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
catch (e) {
|
|
390
|
+
if (e instanceof Error && e.message.includes("layout drift"))
|
|
391
|
+
throw e;
|
|
392
|
+
// Symbol missing in an older library — no check possible.
|
|
393
|
+
}
|
|
394
|
+
return _lib;
|
|
395
|
+
}
|
|
396
|
+
// ---------------------------------------------------------------------------
|
|
397
|
+
// Helpers
|
|
398
|
+
// ---------------------------------------------------------------------------
|
|
399
|
+
/** Process-wide engine settings. Must be set BEFORE constructing a model. */
|
|
400
|
+
exports.Engine = {
|
|
401
|
+
/** Library version string (e.g. "0.2.0"). */
|
|
402
|
+
version() {
|
|
403
|
+
return lib().baseRT_version_string();
|
|
404
|
+
},
|
|
405
|
+
/** Force KV-cache element width: 0=auto, 8=Q8_0, 16=F16. */
|
|
406
|
+
setKvBits(bits) {
|
|
407
|
+
lib().baseRT_set_kv_bits(bits);
|
|
408
|
+
},
|
|
409
|
+
/** Toggle paged-KV mode for subsequent loads. */
|
|
410
|
+
setPagedKv(enable) {
|
|
411
|
+
lib().baseRT_set_paged_kv(enable ? 1 : 0);
|
|
412
|
+
},
|
|
413
|
+
/** Max in-flight batch size for batched decode (sizes logits scratch). */
|
|
414
|
+
setMaxBatchSize(n) {
|
|
415
|
+
lib().baseRT_set_max_batch_size(n);
|
|
416
|
+
},
|
|
417
|
+
/** Override prefill chunk size (tokens/GEMM batch); 0 = per-chip default. */
|
|
418
|
+
setPrefillChunk(n) {
|
|
419
|
+
lib().baseRT_set_prefill_chunk(n);
|
|
420
|
+
},
|
|
421
|
+
/** Paged-weights load policy: 0=auto, 1=force, 2=no-retry (issue #113). */
|
|
422
|
+
setPagedWeights(mode) {
|
|
423
|
+
lib().baseRT_set_paged_weights(mode);
|
|
424
|
+
},
|
|
425
|
+
/** Toggle the baked-decode fast path: true=on (default), false=force live. */
|
|
426
|
+
setBakedDecode(enable) {
|
|
427
|
+
lib().baseRT_set_baked_decode(enable ? 1 : 0);
|
|
428
|
+
},
|
|
429
|
+
/** GPU-wait timeout (ms); 0 = block indefinitely (default). Metal only. */
|
|
430
|
+
setGpuWaitTimeoutMs(ms) {
|
|
431
|
+
lib().baseRT_set_gpu_wait_timeout_ms(ms);
|
|
432
|
+
},
|
|
433
|
+
/** Last thread-local error string, or null. */
|
|
434
|
+
lastError() {
|
|
435
|
+
return lib().baseRT_get_error() || null;
|
|
436
|
+
},
|
|
437
|
+
};
|
|
438
|
+
function cStringFromCharArray(arr) {
|
|
439
|
+
if (typeof arr === "string") {
|
|
440
|
+
const nul = arr.indexOf("\0");
|
|
441
|
+
return nul >= 0 ? arr.slice(0, nul) : arr;
|
|
442
|
+
}
|
|
443
|
+
let s = "";
|
|
444
|
+
for (let i = 0; i < arr.length; i++) {
|
|
445
|
+
const c = arr[i];
|
|
446
|
+
if (c === 0)
|
|
447
|
+
break;
|
|
448
|
+
s += String.fromCharCode(c);
|
|
449
|
+
}
|
|
450
|
+
return s;
|
|
451
|
+
}
|
|
452
|
+
function toModelConfig(c) {
|
|
453
|
+
return {
|
|
454
|
+
dim: c.dim,
|
|
455
|
+
nLayers: c.n_layers,
|
|
456
|
+
nHeads: c.n_heads,
|
|
457
|
+
nKvHeads: c.n_kv_heads,
|
|
458
|
+
headDim: c.head_dim,
|
|
459
|
+
qDim: c.q_dim,
|
|
460
|
+
kvDim: c.kv_dim,
|
|
461
|
+
ffnDim: c.ffn_dim,
|
|
462
|
+
vocabSize: c.vocab_size,
|
|
463
|
+
maxSeqLen: c.max_seq_len,
|
|
464
|
+
normEps: c.norm_eps,
|
|
465
|
+
ropeTheta: c.rope_theta,
|
|
466
|
+
slidingWindowPattern: c.sliding_window_pattern,
|
|
467
|
+
slidingWindow: c.sliding_window,
|
|
468
|
+
ropeLocalTheta: c.rope_local_theta,
|
|
469
|
+
architecture: cStringFromCharArray(c.architecture),
|
|
470
|
+
encNLayers: c.enc_n_layers,
|
|
471
|
+
encNHeads: c.enc_n_heads,
|
|
472
|
+
encDim: c.enc_dim,
|
|
473
|
+
encFfnDim: c.enc_ffn_dim,
|
|
474
|
+
nMels: c.n_mels,
|
|
475
|
+
encMaxSeqLen: c.enc_max_seq_len,
|
|
476
|
+
nExperts: c.n_experts,
|
|
477
|
+
hasVision: c.vision_n_layers > 0,
|
|
478
|
+
hasAudio: c.audio_n_layers > 0,
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
function toSamplingC(opts) {
|
|
482
|
+
const s = {
|
|
483
|
+
temperature: opts?.temperature ?? 0.0,
|
|
484
|
+
top_k: opts?.topK ?? 40,
|
|
485
|
+
top_p: opts?.topP ?? 0.9,
|
|
486
|
+
min_p: opts?.minP ?? 0.0,
|
|
487
|
+
repeat_penalty: opts?.repeatPenalty ?? 1.0,
|
|
488
|
+
presence_penalty: opts?.presencePenalty ?? 0.0,
|
|
489
|
+
frequency_penalty: opts?.frequencyPenalty ?? 0.0,
|
|
490
|
+
seed: opts?.seed ?? 0,
|
|
491
|
+
n_logit_bias: 0,
|
|
492
|
+
logit_bias_tokens: null,
|
|
493
|
+
logit_bias_values: null,
|
|
494
|
+
};
|
|
495
|
+
const lb = opts?.logitBias;
|
|
496
|
+
if (lb && Object.keys(lb).length > 0) {
|
|
497
|
+
const entries = Object.entries(lb);
|
|
498
|
+
const toks = new Int32Array(entries.length);
|
|
499
|
+
const vals = new Float32Array(entries.length);
|
|
500
|
+
entries.forEach(([t, v], i) => {
|
|
501
|
+
toks[i] = parseInt(t, 10);
|
|
502
|
+
vals[i] = v;
|
|
503
|
+
});
|
|
504
|
+
s.n_logit_bias = entries.length;
|
|
505
|
+
s.logit_bias_tokens = toks;
|
|
506
|
+
s.logit_bias_values = vals;
|
|
507
|
+
}
|
|
508
|
+
return s;
|
|
509
|
+
}
|
|
510
|
+
function toGenStats(s) {
|
|
511
|
+
return {
|
|
512
|
+
promptTokens: s.prompt_tokens,
|
|
513
|
+
generatedTokens: s.generated_tokens,
|
|
514
|
+
prefillTimeMs: s.prefill_time_ms,
|
|
515
|
+
decodeTimeMs: s.decode_time_ms,
|
|
516
|
+
prefillTokensPerSec: s.prefill_tokens_per_sec,
|
|
517
|
+
decodeTokensPerSec: s.decode_tokens_per_sec,
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
function toTranscribeStats(s) {
|
|
521
|
+
return {
|
|
522
|
+
nTokens: s.n_tokens,
|
|
523
|
+
audioMs: s.audio_ms,
|
|
524
|
+
encodeMs: s.encode_ms,
|
|
525
|
+
decodeMs: s.decode_ms,
|
|
526
|
+
totalMs: s.total_ms,
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
// ---------------------------------------------------------------------------
|
|
530
|
+
// BaseRTModel
|
|
531
|
+
// ---------------------------------------------------------------------------
|
|
532
|
+
class BaseRTModel {
|
|
533
|
+
/**
|
|
534
|
+
* Load a BaseRT model from a `.base` bundle.
|
|
535
|
+
*
|
|
536
|
+
* @param modelPath Path to the `.base` model file.
|
|
537
|
+
* @param kernelLibraryPath Path to the compiled GPU kernel library (on Metal,
|
|
538
|
+
* baseRT.metallib), or null to auto-detect — the
|
|
539
|
+
* shipped single-file dylib carries it embedded.
|
|
540
|
+
* @param maxContext Maximum context window (0 = model default).
|
|
541
|
+
*/
|
|
542
|
+
constructor(modelPath, kernelLibraryPath = null, maxContext = 0) {
|
|
543
|
+
this._l = lib();
|
|
544
|
+
this._handle = this._l.baseRT_load_model(modelPath, kernelLibraryPath, maxContext);
|
|
545
|
+
if (!this._handle) {
|
|
546
|
+
throw new Error(`Failed to load model: ${this._l.baseRT_get_error() || "unknown error"}`);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
get handle() {
|
|
550
|
+
if (!this._handle)
|
|
551
|
+
throw new Error("Model has been closed");
|
|
552
|
+
return this._handle;
|
|
553
|
+
}
|
|
554
|
+
/** Free all GPU resources. Safe to call multiple times. */
|
|
555
|
+
close() {
|
|
556
|
+
if (this._handle) {
|
|
557
|
+
this._l.baseRT_free_model(this._handle);
|
|
558
|
+
this._handle = null;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
/** Support `using model = new BaseRTModel(...)`. */
|
|
562
|
+
[Symbol.dispose]() {
|
|
563
|
+
this.close();
|
|
564
|
+
}
|
|
565
|
+
// -- Model info ------------------------------------------------------------
|
|
566
|
+
get config() {
|
|
567
|
+
return toModelConfig(this._l.baseRT_get_config(this.handle));
|
|
568
|
+
}
|
|
569
|
+
get memoryUsage() {
|
|
570
|
+
return this._l.baseRT_model_memory(this.handle);
|
|
571
|
+
}
|
|
572
|
+
get isWhisper() {
|
|
573
|
+
return this._l.baseRT_is_whisper(this.handle);
|
|
574
|
+
}
|
|
575
|
+
get position() {
|
|
576
|
+
return this._l.baseRT_get_position(this.handle);
|
|
577
|
+
}
|
|
578
|
+
// -- Tokenization ----------------------------------------------------------
|
|
579
|
+
encode(text, maxTokens = 8192) {
|
|
580
|
+
const buf = new Uint32Array(maxTokens);
|
|
581
|
+
const n = this._l.baseRT_encode(this.handle, text, buf, maxTokens);
|
|
582
|
+
if (n < 0) {
|
|
583
|
+
throw new Error(`encode failed: ${this._l.baseRT_get_error() || "?"}`);
|
|
584
|
+
}
|
|
585
|
+
return Array.from(buf.subarray(0, n));
|
|
586
|
+
}
|
|
587
|
+
tokenCount(text) {
|
|
588
|
+
return this._l.baseRT_token_count(this.handle, text);
|
|
589
|
+
}
|
|
590
|
+
decodeToken(tokenId) {
|
|
591
|
+
return this._l.baseRT_decode_token(this.handle, tokenId) || "";
|
|
592
|
+
}
|
|
593
|
+
// -- Generation ------------------------------------------------------------
|
|
594
|
+
_registerToken(onToken) {
|
|
595
|
+
if (!onToken)
|
|
596
|
+
return null;
|
|
597
|
+
return koffi_1.default.register((tokenId, text, _ud) => onToken(tokenId, text || ""), koffi_1.default.pointer(TokenCallbackC));
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* Generate from a prompt. Blocks until generation completes; `onToken` is
|
|
601
|
+
* invoked synchronously per token (return false to stop early).
|
|
602
|
+
*/
|
|
603
|
+
generate(tokens, maxTokens, sampling, onToken) {
|
|
604
|
+
const arr = tokens instanceof Uint32Array ? tokens : Uint32Array.from(tokens);
|
|
605
|
+
const cb = this._registerToken(onToken);
|
|
606
|
+
try {
|
|
607
|
+
const stats = this._l.baseRT_generate(this.handle, arr, arr.length, maxTokens, toSamplingC(sampling), cb, null);
|
|
608
|
+
return toGenStats(stats);
|
|
609
|
+
}
|
|
610
|
+
finally {
|
|
611
|
+
if (cb)
|
|
612
|
+
koffi_1.default.unregister(cb);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
/** Continue from the current KV cache state (multi-turn). */
|
|
616
|
+
generateContinue(tokens, maxTokens, sampling, onToken) {
|
|
617
|
+
const arr = tokens instanceof Uint32Array ? tokens : Uint32Array.from(tokens);
|
|
618
|
+
const cb = this._registerToken(onToken);
|
|
619
|
+
try {
|
|
620
|
+
const stats = this._l.baseRT_generate_continue(this.handle, arr, arr.length, maxTokens, toSamplingC(sampling), cb, null);
|
|
621
|
+
return toGenStats(stats);
|
|
622
|
+
}
|
|
623
|
+
finally {
|
|
624
|
+
if (cb)
|
|
625
|
+
koffi_1.default.unregister(cb);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
/** Generate and return the full decoded text. */
|
|
629
|
+
generateText(tokens, maxTokens, sampling) {
|
|
630
|
+
const pieces = [];
|
|
631
|
+
this.generate(tokens, maxTokens, sampling, (_id, text) => {
|
|
632
|
+
pieces.push(text);
|
|
633
|
+
return true;
|
|
634
|
+
});
|
|
635
|
+
return pieces.join("");
|
|
636
|
+
}
|
|
637
|
+
// -- Low-level -------------------------------------------------------------
|
|
638
|
+
prefill(tokens) {
|
|
639
|
+
const arr = tokens instanceof Uint32Array ? tokens : Uint32Array.from(tokens);
|
|
640
|
+
// baseRT_prefill returns the first generated token (argmax of prefill
|
|
641
|
+
// logits) with no 0-sentinel; token id 0 is a valid token, so it must not
|
|
642
|
+
// be treated as an error.
|
|
643
|
+
return this._l.baseRT_prefill(this.handle, arr, arr.length);
|
|
644
|
+
}
|
|
645
|
+
prefillImage(tokens, imagePath) {
|
|
646
|
+
const arr = tokens instanceof Uint32Array ? tokens : Uint32Array.from(tokens);
|
|
647
|
+
const t = this._l.baseRT_prefill_image(this.handle, arr, arr.length, imagePath);
|
|
648
|
+
if (t === 0)
|
|
649
|
+
throw new Error(`prefillImage failed: ${this._l.baseRT_get_error() || "?"}`);
|
|
650
|
+
return t;
|
|
651
|
+
}
|
|
652
|
+
imageNumTokens(imagePath) {
|
|
653
|
+
return this._l.baseRT_image_num_tokens(this.handle, imagePath);
|
|
654
|
+
}
|
|
655
|
+
prefillAudio(tokens, pcm) {
|
|
656
|
+
const arr = tokens instanceof Uint32Array ? tokens : Uint32Array.from(tokens);
|
|
657
|
+
const t = this._l.baseRT_prefill_audio(this.handle, arr, arr.length, pcm, pcm.length);
|
|
658
|
+
if (t === 0)
|
|
659
|
+
throw new Error(`prefillAudio failed: ${this._l.baseRT_get_error() || "?"}`);
|
|
660
|
+
return t;
|
|
661
|
+
}
|
|
662
|
+
audioNumTokens(nSamples) {
|
|
663
|
+
return this._l.baseRT_audio_num_tokens(this.handle, nSamples);
|
|
664
|
+
}
|
|
665
|
+
decodeStep(tokenId, position) {
|
|
666
|
+
// baseRT_decode_step returns the sampled token ID with no 0-sentinel;
|
|
667
|
+
// token id 0 is a valid token and must not be treated as an error.
|
|
668
|
+
return this._l.baseRT_decode_step(this.handle, tokenId, position);
|
|
669
|
+
}
|
|
670
|
+
chainDecode(firstToken, startPosition, count) {
|
|
671
|
+
const buf = new Uint32Array(count);
|
|
672
|
+
const n = this._l.baseRT_chain_decode(this.handle, firstToken, startPosition, count, buf);
|
|
673
|
+
if (n < 0)
|
|
674
|
+
throw new Error(`chainDecode failed: ${this._l.baseRT_get_error() || "?"}`);
|
|
675
|
+
return Array.from(buf.subarray(0, n));
|
|
676
|
+
}
|
|
677
|
+
reset() {
|
|
678
|
+
this._l.baseRT_reset(this.handle);
|
|
679
|
+
}
|
|
680
|
+
setSpeculation(enabled) {
|
|
681
|
+
this._l.baseRT_set_speculation(this.handle, enabled);
|
|
682
|
+
}
|
|
683
|
+
// -- Embeddings ------------------------------------------------------------
|
|
684
|
+
get embeddingDim() {
|
|
685
|
+
return this._l.baseRT_embedding_dim(this.handle);
|
|
686
|
+
}
|
|
687
|
+
embed(tokens) {
|
|
688
|
+
const dim = this.embeddingDim;
|
|
689
|
+
const arr = tokens instanceof Uint32Array ? tokens : Uint32Array.from(tokens);
|
|
690
|
+
const out = new Float32Array(dim);
|
|
691
|
+
const n = this._l.baseRT_embed(this.handle, arr, arr.length, out, dim);
|
|
692
|
+
if (n <= 0)
|
|
693
|
+
throw new Error(`embed failed: ${this._l.baseRT_get_error() || "?"}`);
|
|
694
|
+
return Array.from(out.subarray(0, n));
|
|
695
|
+
}
|
|
696
|
+
embedText(text) {
|
|
697
|
+
const dim = this.embeddingDim;
|
|
698
|
+
const out = new Float32Array(dim);
|
|
699
|
+
const n = this._l.baseRT_embed_text(this.handle, text, out, dim);
|
|
700
|
+
if (n <= 0)
|
|
701
|
+
throw new Error(`embedText failed: ${this._l.baseRT_get_error() || "?"}`);
|
|
702
|
+
return Array.from(out.subarray(0, n));
|
|
703
|
+
}
|
|
704
|
+
// -- Chat templates --------------------------------------------------------
|
|
705
|
+
formatChat(system, user) {
|
|
706
|
+
return this._l.baseRT_format_chat(this.handle, system, user) || "";
|
|
707
|
+
}
|
|
708
|
+
get chatTemplate() {
|
|
709
|
+
return this._l.baseRT_chat_template(this.handle) || "";
|
|
710
|
+
}
|
|
711
|
+
// -- Whisper ---------------------------------------------------------------
|
|
712
|
+
setTimestamps(enabled) {
|
|
713
|
+
this._l.baseRT_set_timestamps(this.handle, enabled);
|
|
714
|
+
}
|
|
715
|
+
/** Set the Whisper task: "transcribe" (default) or "translate". */
|
|
716
|
+
setTask(task) {
|
|
717
|
+
if (!this._l.baseRT_set_task(this.handle, task)) {
|
|
718
|
+
throw new Error(`setTask failed: ${this._l.baseRT_get_error() || "unknown error"}`);
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
/** Set an initial prompt to bias Whisper decoding (null clears it). */
|
|
722
|
+
setInitialPrompt(text) {
|
|
723
|
+
this._l.baseRT_set_initial_prompt(this.handle, text);
|
|
724
|
+
}
|
|
725
|
+
/** Condition each 30s window on previous decoded text (default true). */
|
|
726
|
+
setConditionOnPreviousText(enabled) {
|
|
727
|
+
this._l.baseRT_set_condition_on_previous_text(this.handle, enabled);
|
|
728
|
+
}
|
|
729
|
+
/** Language code of the last transcription (detected or requested). */
|
|
730
|
+
transcribeLanguage() {
|
|
731
|
+
return this._l.baseRT_transcribe_language(this.handle) || "";
|
|
732
|
+
}
|
|
733
|
+
/**
|
|
734
|
+
* Duration of the last transcription's source audio in milliseconds (the
|
|
735
|
+
* OpenAI verbose_json `duration` field is this value in fractional
|
|
736
|
+
* seconds). 0 if no transcription has run.
|
|
737
|
+
*/
|
|
738
|
+
transcribeAudioDurationMs() {
|
|
739
|
+
return this._l.baseRT_transcribe_audio_duration_ms(this.handle);
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* Per-segment metadata for the last transcription (verbose_json surface).
|
|
743
|
+
* Empty if no transcription has run. Segment text is copied out, so the
|
|
744
|
+
* returned array stays valid after later transcriptions.
|
|
745
|
+
*/
|
|
746
|
+
transcribeSegments() {
|
|
747
|
+
const n = this._l.baseRT_transcribe_segment_count(this.handle);
|
|
748
|
+
const out = [];
|
|
749
|
+
for (let i = 0; i < n; i++) {
|
|
750
|
+
const seg = {};
|
|
751
|
+
if (!this._l.baseRT_transcribe_segment(this.handle, i, seg))
|
|
752
|
+
break;
|
|
753
|
+
out.push({
|
|
754
|
+
startMs: seg.start_ms,
|
|
755
|
+
endMs: seg.end_ms,
|
|
756
|
+
text: seg.text || "",
|
|
757
|
+
avgLogprob: seg.avg_logprob,
|
|
758
|
+
noSpeechProb: seg.no_speech_prob,
|
|
759
|
+
compressionRatio: seg.compression_ratio,
|
|
760
|
+
temperature: seg.temperature,
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
return out;
|
|
764
|
+
}
|
|
765
|
+
transcribe(wavPath, language) {
|
|
766
|
+
const stats = {};
|
|
767
|
+
const text = this._l.baseRT_transcribe(this.handle, wavPath, language ?? null, stats);
|
|
768
|
+
if (text == null)
|
|
769
|
+
throw new Error(`transcribe failed: ${this._l.baseRT_get_error() || "?"}`);
|
|
770
|
+
return { text, stats: toTranscribeStats(stats) };
|
|
771
|
+
}
|
|
772
|
+
transcribePcm(samples, language) {
|
|
773
|
+
const stats = {};
|
|
774
|
+
const text = this._l.baseRT_transcribe_pcm(this.handle, samples, samples.length, language ?? null, stats);
|
|
775
|
+
if (text == null)
|
|
776
|
+
throw new Error(`transcribePcm failed: ${this._l.baseRT_get_error() || "?"}`);
|
|
777
|
+
return { text, stats: toTranscribeStats(stats) };
|
|
778
|
+
}
|
|
779
|
+
transcribeStream(wavPath, language, onSegment) {
|
|
780
|
+
const stats = {};
|
|
781
|
+
const cb = onSegment
|
|
782
|
+
? koffi_1.default.register((s, e, t, _ud) => onSegment(s, e, t || ""), koffi_1.default.pointer(SegmentCallbackC))
|
|
783
|
+
: null;
|
|
784
|
+
try {
|
|
785
|
+
const text = this._l.baseRT_transcribe_stream(this.handle, wavPath, language ?? null, stats, cb, null);
|
|
786
|
+
return { text: text || "", stats: toTranscribeStats(stats) };
|
|
787
|
+
}
|
|
788
|
+
finally {
|
|
789
|
+
if (cb)
|
|
790
|
+
koffi_1.default.unregister(cb);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
transcribePcmStream(samples, language, onSegment) {
|
|
794
|
+
const stats = {};
|
|
795
|
+
const cb = onSegment
|
|
796
|
+
? koffi_1.default.register((s, e, t, _ud) => onSegment(s, e, t || ""), koffi_1.default.pointer(SegmentCallbackC))
|
|
797
|
+
: null;
|
|
798
|
+
try {
|
|
799
|
+
const text = this._l.baseRT_transcribe_pcm_stream(this.handle, samples, samples.length, language ?? null, stats, cb, null);
|
|
800
|
+
return { text: text || "", stats: toTranscribeStats(stats) };
|
|
801
|
+
}
|
|
802
|
+
finally {
|
|
803
|
+
if (cb)
|
|
804
|
+
koffi_1.default.unregister(cb);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
exports.BaseRTModel = BaseRTModel;
|
|
809
|
+
exports.default = BaseRTModel;
|
|
810
|
+
/**
|
|
811
|
+
* Internal handles exposed for ABI tests only (verifying struct offsets match
|
|
812
|
+
* include/baseRT/types.h). Not part of the public API — do not depend on these.
|
|
813
|
+
*/
|
|
814
|
+
exports.__internal = {
|
|
815
|
+
ModelConfigC,
|
|
816
|
+
SamplingConfigC,
|
|
817
|
+
GenerationStatsC,
|
|
818
|
+
TranscribeStatsC,
|
|
819
|
+
TranscribeSegmentC,
|
|
820
|
+
toSamplingC,
|
|
821
|
+
toModelConfig,
|
|
822
|
+
};
|
|
823
|
+
//# sourceMappingURL=index.js.map
|