webslm 0.9.0 → 0.10.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/README.md +32 -1
- package/dist/ai-sdk/index.d.ts +15 -0
- package/dist/ai-sdk/index.js +19 -0
- package/dist/ai-sdk/transcription-model.d.ts +48 -0
- package/dist/ai-sdk/transcription-model.js +115 -0
- package/dist/audio.d.ts +33 -0
- package/dist/audio.js +87 -0
- package/dist/engine.js +52 -0
- package/dist/hub.d.ts +9 -0
- package/dist/hub.js +12 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -1
- package/dist/models.d.ts +19 -1
- package/dist/models.js +55 -1
- package/dist/native.d.ts +6 -0
- package/dist/protocol.d.ts +31 -0
- package/dist/types.d.ts +68 -0
- package/dist/wasm.d.ts +2 -0
- package/native-manifest.json +29 -29
- package/package.json +1 -1
- package/wasm/relaxed/webslm_wasm.d.ts +30 -3
- package/wasm/relaxed/webslm_wasm.js +75 -15
- package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
- package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +6 -3
- package/wasm/simd/webslm_wasm.d.ts +30 -3
- package/wasm/simd/webslm_wasm.js +75 -15
- package/wasm/simd/webslm_wasm_bg.wasm +0 -0
- package/wasm/simd/webslm_wasm_bg.wasm.d.ts +6 -3
- package/wasm/threads/webslm_wasm.d.ts +31 -4
- package/wasm/threads/webslm_wasm.js +80 -20
- package/wasm/threads/webslm_wasm_bg.wasm +0 -0
- package/wasm/threads/webslm_wasm_bg.wasm.d.ts +7 -4
package/README.md
CHANGED
|
@@ -258,6 +258,19 @@ providerMetadata.webslm.images; // [{ seed, width, height, timeMs }, ...]
|
|
|
258
258
|
|
|
259
259
|
`settings` are the load options of `loadImageModel` and the defaults `steps`, `guidance` and `negativePrompt`; image models of one id and the same load options share the loaded model. Image files and masks (editing) are not supported (an `unsupported` warning). `createWebslm({ imageEngine })` replaces what loads them.
|
|
260
260
|
|
|
261
|
+
Whisper checkpoints are transcription models, behind `transcribe`:
|
|
262
|
+
|
|
263
|
+
```ts
|
|
264
|
+
import { transcribe } from "ai";
|
|
265
|
+
|
|
266
|
+
const { text, language, segments, durationInSeconds } = await transcribe({
|
|
267
|
+
model: webslm.transcriptionModel("openai/whisper-tiny"),
|
|
268
|
+
audio: await fetch("/speech.mp3").then((r) => r.arrayBuffer()),
|
|
269
|
+
});
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
`webslm.transcriptionModel(modelId, settings)` takes the load options too, and `language`, `task` (`"transcribe"` or `"translate"`) and `maxNewTokens` (also per call in `providerOptions.webslm`). Segments are the 30 s windows; word timestamps come back as an `unsupported` warning. Other model ids reject with `UNSUPPORTED_TASK`.
|
|
273
|
+
|
|
261
274
|
`CURATED_MODELS` (also exported by `webslm`) lists checkpoints known to run well, with the sampling their model cards recommend, for a model picker; `searchModels` finds others on the Hub. `ai` and `@ai-sdk/provider` are optional peer dependencies: the main `webslm` entry does not need them. The demo's [AI SDK page](https://maxgfr.github.io/webslm/ai-sdk.html) (`apps/demo/src/ai-sdk.ts`) is a complete example.
|
|
262
275
|
|
|
263
276
|
## Embeddings
|
|
@@ -275,6 +288,24 @@ model.info().embedding; // { dimensions: 384, pooling: ["mean"], normalize: true
|
|
|
275
288
|
|
|
276
289
|
Vectors are pooled and normalized as the checkpoint's sentence-transformers files say (mean pooling and no normalization for a plain checkpoint); `embed(texts, { pooling, normalize })` overrides both for one call (`"cls"`, `"mean"`, `"max"`, `"mean_sqrt_len_tokens"`, `"weightedmean"`, `"lasttoken"`). `vectors` are views on one `Float32Array` (`data`), and `tokens` counts the tokens read from each text: texts longer than `maxLength` are cut. Without `quant`, an encoder loads in f32 (`quant: "q8"` moves the vectors by about 1e-3), on the CPU under `device: "auto"`. The embeddings match sentence-transformers and model2vec within 1.3e-6 of the largest value, in the WebAssembly engine, natively and on the GPU (see the [repository README](../../README.md#embeddings)). `chat`, `generate`, sessions and adapters reject on an encoder with `UNSUPPORTED_TASK`, and `embed` on a language model; `searchModels` and `checkModel` mark embedding models with `embedding: true` (supported when their `model_type` is one of `ENCODER_MODEL_TYPES`).
|
|
277
290
|
|
|
291
|
+
## Speech recognition
|
|
292
|
+
|
|
293
|
+
Whisper checkpoints (`openai/whisper-tiny`, `whisper-tiny.en`, `whisper-base`...) load with `loadModel` and answer `transcribe`: the text, its language, and one segment per 30 s window.
|
|
294
|
+
|
|
295
|
+
```ts
|
|
296
|
+
import { loadModel } from "webslm";
|
|
297
|
+
|
|
298
|
+
const model = await loadModel("openai/whisper-tiny");
|
|
299
|
+
const recording = await fetch("/speech.webm").then((r) => r.blob()); // or a File, an ArrayBuffer, a Uint8Array
|
|
300
|
+
const { text, language, duration, segments } = await model.transcribe(recording, {
|
|
301
|
+
onToken: (piece) => output.append(piece), // the text as it is generated
|
|
302
|
+
});
|
|
303
|
+
await model.transcribe(samples, { sampleRate: 48000, language: "fr", task: "translate" }); // PCM, into English
|
|
304
|
+
model.info().speech; // { sampleRate: 16000, melBins: 80, windowSeconds: 30, multilingual: true, languages: ["en", "zh", ...] }
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
`audio` is mono PCM (`Float32Array`, at `sampleRate`, 16 kHz by default; other rates are resampled) or an audio file (`ArrayBuffer`, `Uint8Array` or `Blob`). WAV files are decoded by the engine everywhere; in a page, other formats (MP3, Ogg, WebM, M4A, whatever the browser plays) are decoded with Web Audio (`OfflineAudioContext`, at 16 kHz, mixed down to mono; `decodeAudio(file)` does it alone). In Node, pass PCM or WAV, and convert other formats with ffmpeg (`ffmpeg -i in.mp3 -ac 1 -ar 16000 out.wav`). `language` is a code (`"en"`), an English name (`"french"`) or a token (`"<|fr|>"`), detected from the first window when absent (English-only checkpoints take English only); `task: "translate"` translates into English; `maxNewTokens` caps each window; `signal` stops the transcription (`ABORTED`). Without `quant`, a speech model loads in f32. The greedy tokens are those of `transformers` exactly, in the WebAssembly engine, natively and on the GPU (see the [repository README](../../README.md#speech-recognition)). Other calls reject on a speech model with `UNSUPPORTED_TASK`, and `transcribe` on other models; `searchModels` and `checkModel` mark Whisper repositories with `speech: true` (`SPEECH_MODEL_TYPES`).
|
|
308
|
+
|
|
278
309
|
## Advanced API
|
|
279
310
|
|
|
280
311
|
The simple API above is built on `loadModel`, `Model` and `Session`, which expose every option.
|
|
@@ -541,7 +572,7 @@ export default defineConfig({
|
|
|
541
572
|
});
|
|
542
573
|
```
|
|
543
574
|
|
|
544
|
-
Server code that imports webslm must not be bundled: webslm runs from its own files in `node_modules` (Next.js: `serverExternalPackages: ["webslm"]`). Without a bundler, a page can import it from jsDelivr (`https://cdn.jsdelivr.net/npm/webslm@0.
|
|
575
|
+
Server code that imports webslm must not be bundled: webslm runs from its own files in `node_modules` (Next.js: `serverExternalPackages: ["webslm"]`). Without a bundler, a page can import it from jsDelivr (`https://cdn.jsdelivr.net/npm/webslm@0.10.0/dist/index.js`); webslm starts its workers through same-origin `blob:` workers when its files come from another origin. Guides for Next.js, Vite, webpack, Node servers, Bun, Deno and CDNs, each with a tested example: <https://github.com/maxgfr/webslm#frameworks-bundlers-and-runtimes>.
|
|
545
576
|
|
|
546
577
|
## Errors
|
|
547
578
|
|
package/dist/ai-sdk/index.d.ts
CHANGED
|
@@ -38,6 +38,17 @@
|
|
|
38
38
|
* });
|
|
39
39
|
* ```
|
|
40
40
|
*
|
|
41
|
+
* Whisper checkpoints are transcription models, behind `transcribe`:
|
|
42
|
+
*
|
|
43
|
+
* ```ts
|
|
44
|
+
* import { transcribe } from "ai";
|
|
45
|
+
*
|
|
46
|
+
* const { text } = await transcribe({
|
|
47
|
+
* model: webslm.transcriptionModel("openai/whisper-tiny"),
|
|
48
|
+
* audio: wavBytes,
|
|
49
|
+
* });
|
|
50
|
+
* ```
|
|
51
|
+
*
|
|
41
52
|
* `ai` (v7) and `@ai-sdk/provider` (v4) are optional peer dependencies of
|
|
42
53
|
* `webslm`: install them to use this entry point.
|
|
43
54
|
*
|
|
@@ -47,6 +58,7 @@ import type { ProviderV4 } from "@ai-sdk/provider";
|
|
|
47
58
|
import { WebslmEmbeddingModel, type WebslmEmbeddingSettings } from "./embedding-model.js";
|
|
48
59
|
import { WebslmImageModel, type WebslmImageEngine, type WebslmImageModelSettings } from "./image-model.js";
|
|
49
60
|
import { WebslmLanguageModel, type WebslmModelSettings } from "./language-model.js";
|
|
61
|
+
import { WebslmTranscriptionModel, type WebslmTranscriptionSettings } from "./transcription-model.js";
|
|
50
62
|
import { type WebslmEngine, type WebslmLoadOptions } from "./loader.js";
|
|
51
63
|
export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, type CheckpointTraits, type CuratedModel, type SamplingDefaults, type SamplingSet, } from "../curated.js";
|
|
52
64
|
export { searchModels, type HubModel, type SearchModelsOptions } from "../hub.js";
|
|
@@ -54,6 +66,7 @@ export { DEFAULT_MODEL } from "../simple.js";
|
|
|
54
66
|
export type { LoadModelOptions, LoadProgress, ModelInfo } from "../types.js";
|
|
55
67
|
export { WebslmLanguageModel, type WebslmCallSettings, type WebslmModelSettings, type WebslmPreloadOptions, } from "./language-model.js";
|
|
56
68
|
export { WebslmEmbeddingModel, type WebslmEmbeddingCallSettings, type WebslmEmbeddingSettings, } from "./embedding-model.js";
|
|
69
|
+
export { WebslmTranscriptionModel, type WebslmTranscriptionCallSettings, type WebslmTranscriptionSettings, } from "./transcription-model.js";
|
|
57
70
|
export type { WebslmEngine, WebslmLoadOptions } from "./loader.js";
|
|
58
71
|
export { MAX_IMAGES_PER_CALL, WebslmImageModel, type WebslmImageEngine, type WebslmImageLoadOptions, type WebslmImageModelSettings, } from "./image-model.js";
|
|
59
72
|
export { DEFAULT_IMAGE_MODEL } from "../image.js";
|
|
@@ -84,6 +97,8 @@ export interface WebslmProvider extends ProviderV4 {
|
|
|
84
97
|
* models of one id and the same load options share one loaded model.
|
|
85
98
|
*/
|
|
86
99
|
imageModel(modelId: string, settings?: WebslmImageModelSettings): WebslmImageModel;
|
|
100
|
+
/** A speech recognition model (Whisper) as a transcription model, for `transcribe`. */
|
|
101
|
+
transcriptionModel(modelId: string, settings?: WebslmTranscriptionSettings): WebslmTranscriptionModel;
|
|
87
102
|
/** Frees every model this provider loaded (each loads again on its next call). */
|
|
88
103
|
unloadAll(): Promise<void>;
|
|
89
104
|
}
|
package/dist/ai-sdk/index.js
CHANGED
|
@@ -38,6 +38,17 @@
|
|
|
38
38
|
* });
|
|
39
39
|
* ```
|
|
40
40
|
*
|
|
41
|
+
* Whisper checkpoints are transcription models, behind `transcribe`:
|
|
42
|
+
*
|
|
43
|
+
* ```ts
|
|
44
|
+
* import { transcribe } from "ai";
|
|
45
|
+
*
|
|
46
|
+
* const { text } = await transcribe({
|
|
47
|
+
* model: webslm.transcriptionModel("openai/whisper-tiny"),
|
|
48
|
+
* audio: wavBytes,
|
|
49
|
+
* });
|
|
50
|
+
* ```
|
|
51
|
+
*
|
|
41
52
|
* `ai` (v7) and `@ai-sdk/provider` (v4) are optional peer dependencies of
|
|
42
53
|
* `webslm`: install them to use this entry point.
|
|
43
54
|
*
|
|
@@ -49,12 +60,14 @@ import { loadModel } from "../models.js";
|
|
|
49
60
|
import { EMBEDDING_SETTING_KEYS, WebslmEmbeddingModel, } from "./embedding-model.js";
|
|
50
61
|
import { ImageModelSlot, WebslmImageModel, } from "./image-model.js";
|
|
51
62
|
import { CALL_SETTING_KEYS, WebslmLanguageModel } from "./language-model.js";
|
|
63
|
+
import { TRANSCRIPTION_SETTING_KEYS, WebslmTranscriptionModel, } from "./transcription-model.js";
|
|
52
64
|
import { ModelSlot, pickLoadOptions, slotKey, } from "./loader.js";
|
|
53
65
|
export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, } from "../curated.js";
|
|
54
66
|
export { searchModels } from "../hub.js";
|
|
55
67
|
export { DEFAULT_MODEL } from "../simple.js";
|
|
56
68
|
export { WebslmLanguageModel, } from "./language-model.js";
|
|
57
69
|
export { WebslmEmbeddingModel, } from "./embedding-model.js";
|
|
70
|
+
export { WebslmTranscriptionModel, } from "./transcription-model.js";
|
|
58
71
|
export { MAX_IMAGES_PER_CALL, WebslmImageModel, } from "./image-model.js";
|
|
59
72
|
export { DEFAULT_IMAGE_MODEL } from "../image.js";
|
|
60
73
|
function checkModelId(modelId) {
|
|
@@ -111,12 +124,18 @@ export function createWebslm(options = {}) {
|
|
|
111
124
|
const loadOptions = { ...options.loadOptions, ...pickLoadOptions(settings, EMBEDDING_SETTING_KEYS) };
|
|
112
125
|
return new WebslmEmbeddingModel(id, slotFor(id, loadOptions), settings);
|
|
113
126
|
};
|
|
127
|
+
const transcriptionModel = (modelId, settings = {}) => {
|
|
128
|
+
const id = checkModelId(modelId);
|
|
129
|
+
const loadOptions = { ...options.loadOptions, ...pickLoadOptions(settings, TRANSCRIPTION_SETTING_KEYS) };
|
|
130
|
+
return new WebslmTranscriptionModel(id, slotFor(id, loadOptions), settings);
|
|
131
|
+
};
|
|
114
132
|
const provider = (modelId, settings) => languageModel(modelId, settings);
|
|
115
133
|
return Object.assign(provider, {
|
|
116
134
|
specificationVersion: "v4",
|
|
117
135
|
languageModel,
|
|
118
136
|
embeddingModel,
|
|
119
137
|
imageModel,
|
|
138
|
+
transcriptionModel,
|
|
120
139
|
unloadAll: async () => {
|
|
121
140
|
const all = [...slots.values()];
|
|
122
141
|
await Promise.all([...all.map((slot) => slot.unload()), ...[...imageSlots.values()].map((slot) => slot.unload())]);
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/** The AI SDK transcription model (specification v4) over a webslm speech recognition model (Whisper). */
|
|
2
|
+
import type { TranscriptionModelV4, TranscriptionModelV4CallOptions, TranscriptionModelV4Result } from "@ai-sdk/provider";
|
|
3
|
+
import type { LoadModelOptions, ModelInfo } from "../types.js";
|
|
4
|
+
import { type ModelSlot } from "./loader.js";
|
|
5
|
+
import type { WebslmPreloadOptions } from "./language-model.js";
|
|
6
|
+
/** Defaults of every `transcribe` call; a call's `providerOptions.webslm` takes precedence. */
|
|
7
|
+
export interface WebslmTranscriptionCallSettings {
|
|
8
|
+
/** The spoken language: a code (`"en"`) or an English name (default: detected). */
|
|
9
|
+
readonly language?: string;
|
|
10
|
+
/** `"transcribe"` (default), or `"translate"` into English. */
|
|
11
|
+
readonly task?: "transcribe" | "translate";
|
|
12
|
+
/** Largest number of tokens per 30 s window. */
|
|
13
|
+
readonly maxNewTokens?: number;
|
|
14
|
+
}
|
|
15
|
+
/** Settings of `webslm.transcriptionModel(modelId, settings)`: how to load the model, and call defaults. */
|
|
16
|
+
export interface WebslmTranscriptionSettings extends Omit<LoadModelOptions, "signal">, WebslmTranscriptionCallSettings {
|
|
17
|
+
}
|
|
18
|
+
/** The fields of {@link WebslmTranscriptionSettings} that are not load options. */
|
|
19
|
+
export declare const TRANSCRIPTION_SETTING_KEYS: readonly ["language", "task", "maxNewTokens"];
|
|
20
|
+
/**
|
|
21
|
+
* An AI SDK transcription model backed by a webslm speech recognition model
|
|
22
|
+
* (Whisper), loaded on the first call and shared by every model of the
|
|
23
|
+
* provider with the same id and load options. Calls run one at a time.
|
|
24
|
+
* WAV audio is decoded everywhere; other formats need Web Audio (browsers).
|
|
25
|
+
*
|
|
26
|
+
* ```ts
|
|
27
|
+
* import { webslm } from "webslm/ai-sdk";
|
|
28
|
+
* import { transcribe } from "ai";
|
|
29
|
+
*
|
|
30
|
+
* const { text, language, segments } = await transcribe({
|
|
31
|
+
* model: webslm.transcriptionModel("openai/whisper-tiny"),
|
|
32
|
+
* audio: await readFile("speech.wav"),
|
|
33
|
+
* });
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
export declare class WebslmTranscriptionModel implements TranscriptionModelV4 {
|
|
37
|
+
#private;
|
|
38
|
+
readonly specificationVersion: "v4";
|
|
39
|
+
readonly provider = "webslm";
|
|
40
|
+
readonly modelId: string;
|
|
41
|
+
/** @internal Built by the provider (`webslm.transcriptionModel(id)`). */
|
|
42
|
+
constructor(modelId: string, slot: ModelSlot, settings?: WebslmTranscriptionSettings);
|
|
43
|
+
/** Downloads and loads the model now instead of at the first call; resolves to its description. */
|
|
44
|
+
load(options?: WebslmPreloadOptions): Promise<ModelInfo>;
|
|
45
|
+
/** Frees the model (once the call in progress ends); the next call loads it again. */
|
|
46
|
+
unload(): Promise<void>;
|
|
47
|
+
doGenerate(options: TranscriptionModelV4CallOptions): Promise<TranscriptionModelV4Result>;
|
|
48
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/** The AI SDK transcription model (specification v4) over a webslm speech recognition model (Whisper). */
|
|
2
|
+
import { WebslmError, toWebslmError } from "../errors.js";
|
|
3
|
+
import { abortReason, raceAbort } from "./loader.js";
|
|
4
|
+
const PROVIDER = "webslm";
|
|
5
|
+
/** The fields of {@link WebslmTranscriptionSettings} that are not load options. */
|
|
6
|
+
export const TRANSCRIPTION_SETTING_KEYS = ["language", "task", "maxNewTokens"];
|
|
7
|
+
/** `providerOptions.webslm` of a call, read leniently (unknown keys and wrong types are ignored). */
|
|
8
|
+
function callSettings(options) {
|
|
9
|
+
const raw = options.providerOptions?.[PROVIDER];
|
|
10
|
+
if (raw === undefined)
|
|
11
|
+
return {};
|
|
12
|
+
const out = {};
|
|
13
|
+
if (typeof raw.language === "string")
|
|
14
|
+
out.language = raw.language;
|
|
15
|
+
if (raw.task === "transcribe" || raw.task === "translate")
|
|
16
|
+
out.task = raw.task;
|
|
17
|
+
if (typeof raw.maxNewTokens === "number")
|
|
18
|
+
out.maxNewTokens = raw.maxNewTokens;
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
/** The bytes of a base64 string. */
|
|
22
|
+
function fromBase64(data) {
|
|
23
|
+
const binary = atob(data);
|
|
24
|
+
const bytes = new Uint8Array(binary.length);
|
|
25
|
+
for (let i = 0; i < binary.length; i++)
|
|
26
|
+
bytes[i] = binary.charCodeAt(i);
|
|
27
|
+
return bytes;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* An AI SDK transcription model backed by a webslm speech recognition model
|
|
31
|
+
* (Whisper), loaded on the first call and shared by every model of the
|
|
32
|
+
* provider with the same id and load options. Calls run one at a time.
|
|
33
|
+
* WAV audio is decoded everywhere; other formats need Web Audio (browsers).
|
|
34
|
+
*
|
|
35
|
+
* ```ts
|
|
36
|
+
* import { webslm } from "webslm/ai-sdk";
|
|
37
|
+
* import { transcribe } from "ai";
|
|
38
|
+
*
|
|
39
|
+
* const { text, language, segments } = await transcribe({
|
|
40
|
+
* model: webslm.transcriptionModel("openai/whisper-tiny"),
|
|
41
|
+
* audio: await readFile("speech.wav"),
|
|
42
|
+
* });
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
export class WebslmTranscriptionModel {
|
|
46
|
+
specificationVersion = "v4";
|
|
47
|
+
provider = PROVIDER;
|
|
48
|
+
modelId;
|
|
49
|
+
#slot;
|
|
50
|
+
#settings;
|
|
51
|
+
/** @internal Built by the provider (`webslm.transcriptionModel(id)`). */
|
|
52
|
+
constructor(modelId, slot, settings = {}) {
|
|
53
|
+
this.modelId = modelId;
|
|
54
|
+
this.#slot = slot;
|
|
55
|
+
this.#settings = settings;
|
|
56
|
+
}
|
|
57
|
+
/** Downloads and loads the model now instead of at the first call; resolves to its description. */
|
|
58
|
+
async load(options = {}) {
|
|
59
|
+
const loaded = await this.#slot.acquire(options.signal, [this.#settings.onProgress, options.onProgress]);
|
|
60
|
+
return loaded.model.info();
|
|
61
|
+
}
|
|
62
|
+
/** Frees the model (once the call in progress ends); the next call loads it again. */
|
|
63
|
+
unload() {
|
|
64
|
+
return this.#slot.unload();
|
|
65
|
+
}
|
|
66
|
+
async doGenerate(options) {
|
|
67
|
+
const signal = options.abortSignal;
|
|
68
|
+
try {
|
|
69
|
+
const loaded = await this.#slot.acquire(signal, [this.#settings.onProgress]);
|
|
70
|
+
if (loaded.model.info().speech === undefined) {
|
|
71
|
+
throw new WebslmError("UNSUPPORTED_TASK", `${this.modelId} is not a speech recognition model; transcription needs one (Whisper)`);
|
|
72
|
+
}
|
|
73
|
+
const warnings = [];
|
|
74
|
+
if (options.timestampGranularities?.includes("word") === true) {
|
|
75
|
+
warnings.push({
|
|
76
|
+
type: "unsupported",
|
|
77
|
+
feature: "timestampGranularities",
|
|
78
|
+
details: "webslm returns one segment per 30 s window, without word timings",
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
const audio = typeof options.audio === "string" ? fromBase64(options.audio) : options.audio;
|
|
82
|
+
const call = { ...pickCallSettings(this.#settings), ...callSettings(options) };
|
|
83
|
+
const result = await raceAbort(loaded.lock.run(async () => {
|
|
84
|
+
if (signal?.aborted === true)
|
|
85
|
+
throw abortReason(signal);
|
|
86
|
+
return loaded.model.transcribe(audio, { ...call, ...(signal === undefined ? {} : { signal }) });
|
|
87
|
+
}), signal);
|
|
88
|
+
return {
|
|
89
|
+
text: result.text,
|
|
90
|
+
segments: result.segments
|
|
91
|
+
.filter((s) => s.text.trim() !== "")
|
|
92
|
+
.map((s) => ({ text: s.text.trim(), startSecond: s.start, endSecond: s.end })),
|
|
93
|
+
language: result.language,
|
|
94
|
+
durationInSeconds: result.duration,
|
|
95
|
+
warnings,
|
|
96
|
+
usage: { tokens: result.tokens, seconds: result.duration },
|
|
97
|
+
response: { timestamp: new Date(), modelId: this.modelId },
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
if (signal?.aborted === true)
|
|
102
|
+
throw abortReason(signal);
|
|
103
|
+
if (error instanceof DOMException)
|
|
104
|
+
throw error;
|
|
105
|
+
throw toWebslmError(error);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
function pickCallSettings(settings) {
|
|
110
|
+
return {
|
|
111
|
+
...(settings.language === undefined ? {} : { language: settings.language }),
|
|
112
|
+
...(settings.task === undefined ? {} : { task: settings.task }),
|
|
113
|
+
...(settings.maxNewTokens === undefined ? {} : { maxNewTokens: settings.maxNewTokens }),
|
|
114
|
+
};
|
|
115
|
+
}
|
package/dist/audio.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Audio for speech recognition, turned into what the engine reads: mono PCM
|
|
3
|
+
* samples (`Float32Array`) or the bytes of a WAV file, which the engine
|
|
4
|
+
* decodes itself (16-bit, 24-bit, 32-bit and float PCM, any channel count,
|
|
5
|
+
* any rate).
|
|
6
|
+
*
|
|
7
|
+
* Other formats (MP3, Ogg, WebM, M4A...) are decoded where the caller's
|
|
8
|
+
* objects live with Web Audio (`OfflineAudioContext.decodeAudioData`, which
|
|
9
|
+
* resamples to 16 kHz), then mixed down to mono. Node has no Web Audio: pass
|
|
10
|
+
* PCM or WAV there (ffmpeg converts anything: `ffmpeg -i in.mp3 -ac 1 -ar
|
|
11
|
+
* 16000 out.wav`).
|
|
12
|
+
*/
|
|
13
|
+
import type { AudioInput } from "./types.js";
|
|
14
|
+
/** The sample rate Whisper reads; other rates are resampled. */
|
|
15
|
+
export declare const SPEECH_SAMPLE_RATE = 16000;
|
|
16
|
+
/** Whether `bytes` start like a RIFF/WAVE (or RF64) file. */
|
|
17
|
+
export declare function isWav(bytes: Uint8Array): boolean;
|
|
18
|
+
/**
|
|
19
|
+
* Decodes an encoded audio file into mono samples at `sampleRate` (16 kHz
|
|
20
|
+
* by default) with Web Audio. Browsers only: rejects with
|
|
21
|
+
* `INVALID_ARGUMENT` where there is no `OfflineAudioContext` (Node, Web
|
|
22
|
+
* Workers).
|
|
23
|
+
*/
|
|
24
|
+
export declare function decodeAudio(input: ArrayBuffer | Uint8Array | Blob, sampleRate?: number): Promise<Float32Array>;
|
|
25
|
+
/**
|
|
26
|
+
* What the engine reads for `input`: PCM samples as they are, WAV bytes as
|
|
27
|
+
* they are, other files decoded to 16 kHz mono samples with Web Audio.
|
|
28
|
+
* Returns the sample rate of PCM it produced (`undefined` for WAV bytes).
|
|
29
|
+
*/
|
|
30
|
+
export declare function prepareAudio(input: AudioInput, sampleRate: number | undefined): Promise<{
|
|
31
|
+
readonly audio: Float32Array | Uint8Array;
|
|
32
|
+
readonly sampleRate?: number;
|
|
33
|
+
}>;
|
package/dist/audio.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Audio for speech recognition, turned into what the engine reads: mono PCM
|
|
3
|
+
* samples (`Float32Array`) or the bytes of a WAV file, which the engine
|
|
4
|
+
* decodes itself (16-bit, 24-bit, 32-bit and float PCM, any channel count,
|
|
5
|
+
* any rate).
|
|
6
|
+
*
|
|
7
|
+
* Other formats (MP3, Ogg, WebM, M4A...) are decoded where the caller's
|
|
8
|
+
* objects live with Web Audio (`OfflineAudioContext.decodeAudioData`, which
|
|
9
|
+
* resamples to 16 kHz), then mixed down to mono. Node has no Web Audio: pass
|
|
10
|
+
* PCM or WAV there (ffmpeg converts anything: `ffmpeg -i in.mp3 -ac 1 -ar
|
|
11
|
+
* 16000 out.wav`).
|
|
12
|
+
*/
|
|
13
|
+
import { WebslmError } from "./errors.js";
|
|
14
|
+
/** The sample rate Whisper reads; other rates are resampled. */
|
|
15
|
+
export const SPEECH_SAMPLE_RATE = 16000;
|
|
16
|
+
/** Whether `bytes` start like a RIFF/WAVE (or RF64) file. */
|
|
17
|
+
export function isWav(bytes) {
|
|
18
|
+
if (bytes.length < 12)
|
|
19
|
+
return false;
|
|
20
|
+
const tag = (at) => String.fromCharCode(bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]);
|
|
21
|
+
return (tag(0) === "RIFF" || tag(0) === "RF64") && tag(8) === "WAVE";
|
|
22
|
+
}
|
|
23
|
+
/** `OfflineAudioContext`, when the environment has Web Audio. */
|
|
24
|
+
function offlineAudioContext() {
|
|
25
|
+
const g = globalThis;
|
|
26
|
+
return g.OfflineAudioContext ?? g.webkitOfflineAudioContext;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Decodes an encoded audio file into mono samples at `sampleRate` (16 kHz
|
|
30
|
+
* by default) with Web Audio. Browsers only: rejects with
|
|
31
|
+
* `INVALID_ARGUMENT` where there is no `OfflineAudioContext` (Node, Web
|
|
32
|
+
* Workers).
|
|
33
|
+
*/
|
|
34
|
+
export async function decodeAudio(input, sampleRate = SPEECH_SAMPLE_RATE) {
|
|
35
|
+
const Context = offlineAudioContext();
|
|
36
|
+
if (Context === undefined) {
|
|
37
|
+
throw new WebslmError("INVALID_ARGUMENT", "this environment has no Web Audio to decode the file: pass mono PCM samples (Float32Array) or a WAV file " +
|
|
38
|
+
"(ffmpeg converts other formats: ffmpeg -i in.mp3 -ac 1 -ar 16000 out.wav)");
|
|
39
|
+
}
|
|
40
|
+
const bytes = await toBytes(input);
|
|
41
|
+
// decodeAudioData detaches its buffer: give it a copy.
|
|
42
|
+
const copy = bytes.slice().buffer;
|
|
43
|
+
let buffer;
|
|
44
|
+
try {
|
|
45
|
+
buffer = await new Context(1, 1, sampleRate).decodeAudioData(copy);
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
49
|
+
throw new WebslmError("INVALID_ARGUMENT", `cannot decode the audio file: ${message}`);
|
|
50
|
+
}
|
|
51
|
+
const channels = buffer.numberOfChannels;
|
|
52
|
+
if (channels === 1)
|
|
53
|
+
return buffer.getChannelData(0).slice();
|
|
54
|
+
const mono = new Float32Array(buffer.length);
|
|
55
|
+
for (let c = 0; c < channels; c++) {
|
|
56
|
+
const data = buffer.getChannelData(c);
|
|
57
|
+
for (let i = 0; i < mono.length; i++)
|
|
58
|
+
mono[i] = mono[i] + data[i] / channels;
|
|
59
|
+
}
|
|
60
|
+
return mono;
|
|
61
|
+
}
|
|
62
|
+
async function toBytes(input) {
|
|
63
|
+
if (input instanceof Uint8Array)
|
|
64
|
+
return input;
|
|
65
|
+
if (input instanceof ArrayBuffer)
|
|
66
|
+
return new Uint8Array(input);
|
|
67
|
+
if (typeof Blob !== "undefined" && input instanceof Blob)
|
|
68
|
+
return new Uint8Array(await input.arrayBuffer());
|
|
69
|
+
throw new WebslmError("INVALID_ARGUMENT", "audio must be a Float32Array, an ArrayBuffer, a Uint8Array or a Blob");
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* What the engine reads for `input`: PCM samples as they are, WAV bytes as
|
|
73
|
+
* they are, other files decoded to 16 kHz mono samples with Web Audio.
|
|
74
|
+
* Returns the sample rate of PCM it produced (`undefined` for WAV bytes).
|
|
75
|
+
*/
|
|
76
|
+
export async function prepareAudio(input, sampleRate) {
|
|
77
|
+
if (input instanceof Float32Array) {
|
|
78
|
+
return { audio: input, ...(sampleRate === undefined ? {} : { sampleRate }) };
|
|
79
|
+
}
|
|
80
|
+
if (ArrayBuffer.isView(input) && !(input instanceof Uint8Array)) {
|
|
81
|
+
throw new WebslmError("INVALID_ARGUMENT", "audio must be a Float32Array of samples, or an ArrayBuffer, Uint8Array or Blob holding a file");
|
|
82
|
+
}
|
|
83
|
+
const bytes = await toBytes(input);
|
|
84
|
+
if (isWav(bytes))
|
|
85
|
+
return { audio: bytes };
|
|
86
|
+
return { audio: await decodeAudio(bytes, SPEECH_SAMPLE_RATE), sampleRate: SPEECH_SAMPLE_RATE };
|
|
87
|
+
}
|
package/dist/engine.js
CHANGED
|
@@ -234,6 +234,8 @@ export class Engine {
|
|
|
234
234
|
const result = await this.#generateImage(request, signal);
|
|
235
235
|
return [result, result.rgba.buffer instanceof ArrayBuffer ? [result.rgba.buffer] : []];
|
|
236
236
|
}
|
|
237
|
+
case "transcribe":
|
|
238
|
+
return [await this.#transcribe(request, signal)];
|
|
237
239
|
case "unload": {
|
|
238
240
|
const image = this.#imageModels.get(request.model);
|
|
239
241
|
if (image !== undefined) {
|
|
@@ -304,6 +306,56 @@ export class Engine {
|
|
|
304
306
|
: target.generate(request.prompt, options, onDelta, onPrefill)));
|
|
305
307
|
return withTimings(summary, started, first, last);
|
|
306
308
|
}
|
|
309
|
+
/**
|
|
310
|
+
* Transcribes speech: pieces of text stream as `delta` messages (`token`
|
|
311
|
+
* -1), and the signal stops the transcription before its next token.
|
|
312
|
+
*/
|
|
313
|
+
async #transcribe(request, signal) {
|
|
314
|
+
const { handle } = this.#model(request.model);
|
|
315
|
+
const options = JSON.stringify(request.options);
|
|
316
|
+
const post = (text) => this.#host.post({ type: "delta", id: request.id, text, token: -1 });
|
|
317
|
+
if (handle.runtime === "wasm") {
|
|
318
|
+
const onText = async (text) => {
|
|
319
|
+
post(text);
|
|
320
|
+
// Let `abort` messages in before the next token.
|
|
321
|
+
await yieldToEventLoop();
|
|
322
|
+
return !signal.aborted;
|
|
323
|
+
};
|
|
324
|
+
return (await handle.model.transcribe(request.audio, options, onText));
|
|
325
|
+
}
|
|
326
|
+
if (handle.model.transcribe === undefined) {
|
|
327
|
+
throw new WebslmError("UNSUPPORTED_TASK", "this build of the native engine cannot transcribe");
|
|
328
|
+
}
|
|
329
|
+
const cancel = new handle.addon.CancelToken();
|
|
330
|
+
const onAbort = () => cancel.cancel();
|
|
331
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
332
|
+
if (signal.aborted)
|
|
333
|
+
cancel.cancel();
|
|
334
|
+
// The result and the text come through different queues: wait for
|
|
335
|
+
// every piece the result counts.
|
|
336
|
+
let received = 0;
|
|
337
|
+
let expected = Number.POSITIVE_INFINITY;
|
|
338
|
+
let allReceived = () => { };
|
|
339
|
+
const done = new Promise((resolve) => {
|
|
340
|
+
allReceived = resolve;
|
|
341
|
+
});
|
|
342
|
+
const onText = (text) => {
|
|
343
|
+
post(text);
|
|
344
|
+
received += 1;
|
|
345
|
+
if (received >= expected)
|
|
346
|
+
allReceived();
|
|
347
|
+
};
|
|
348
|
+
try {
|
|
349
|
+
const { pieces, ...result } = (await handle.model.transcribe(request.audio, options, onText, cancel));
|
|
350
|
+
expected = pieces;
|
|
351
|
+
if (received < expected)
|
|
352
|
+
await done;
|
|
353
|
+
return result;
|
|
354
|
+
}
|
|
355
|
+
finally {
|
|
356
|
+
signal.removeEventListener("abort", onAbort);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
307
359
|
/**
|
|
308
360
|
* A generation on the native engine: tokens arrive from the model's thread
|
|
309
361
|
* through a threadsafe function, and the signal cancels the call (before
|
package/dist/hub.d.ts
CHANGED
|
@@ -17,6 +17,8 @@ export declare const SUPPORTED_MODEL_TYPES: readonly string[];
|
|
|
17
17
|
* MiniLM, ModernBERT and its descendants, model2vec static embeddings).
|
|
18
18
|
*/
|
|
19
19
|
export declare const ENCODER_MODEL_TYPES: readonly string[];
|
|
20
|
+
/** `model_type` values of the speech recognition models the engine transcribes with (Whisper). */
|
|
21
|
+
export declare const SPEECH_MODEL_TYPES: readonly string[];
|
|
20
22
|
/** Files read besides the weights, when the repository has them. */
|
|
21
23
|
export declare const CHECKPOINT_SIDE_FILES: readonly string[];
|
|
22
24
|
export declare const SAFETENSORS_INDEX = "model.safetensors.index.json";
|
|
@@ -151,6 +153,11 @@ export interface HubModel {
|
|
|
151
153
|
* {@link ENCODER_MODEL_TYPES} (load it and call `embed`), refused otherwise.
|
|
152
154
|
*/
|
|
153
155
|
readonly embedding?: boolean;
|
|
156
|
+
/**
|
|
157
|
+
* Whether it is a speech recognition model (one of
|
|
158
|
+
* {@link SPEECH_MODEL_TYPES}: load it and call `transcribe`).
|
|
159
|
+
*/
|
|
160
|
+
readonly speech?: boolean;
|
|
154
161
|
/** Why it is not supported. */
|
|
155
162
|
readonly reason?: string;
|
|
156
163
|
readonly downloads?: number;
|
|
@@ -221,6 +228,8 @@ export interface ModelCheck {
|
|
|
221
228
|
* one of {@link ENCODER_MODEL_TYPES} (load it and call `embed`).
|
|
222
229
|
*/
|
|
223
230
|
readonly embedding?: boolean;
|
|
231
|
+
/** Whether it is a speech recognition model (load it and call `transcribe`). */
|
|
232
|
+
readonly speech?: boolean;
|
|
224
233
|
readonly modelType?: string;
|
|
225
234
|
readonly gated: false | "auto" | "manual";
|
|
226
235
|
readonly hasTokenizer: boolean;
|
package/dist/hub.js
CHANGED
|
@@ -29,6 +29,8 @@ export const SUPPORTED_MODEL_TYPES = [
|
|
|
29
29
|
* MiniLM, ModernBERT and its descendants, model2vec static embeddings).
|
|
30
30
|
*/
|
|
31
31
|
export const ENCODER_MODEL_TYPES = ["bert", "modernbert", "model2vec"];
|
|
32
|
+
/** `model_type` values of the speech recognition models the engine transcribes with (Whisper). */
|
|
33
|
+
export const SPEECH_MODEL_TYPES = ["whisper"];
|
|
32
34
|
/** Files read besides the weights, when the repository has them. */
|
|
33
35
|
export const CHECKPOINT_SIDE_FILES = [
|
|
34
36
|
"config.json",
|
|
@@ -349,8 +351,11 @@ export function estimateMemory(params) {
|
|
|
349
351
|
export function unsupportedReason(modelType) {
|
|
350
352
|
if (modelType === undefined)
|
|
351
353
|
return "no config.json model_type published";
|
|
352
|
-
if (SUPPORTED_MODEL_TYPES.includes(modelType) ||
|
|
354
|
+
if (SUPPORTED_MODEL_TYPES.includes(modelType) ||
|
|
355
|
+
ENCODER_MODEL_TYPES.includes(modelType) ||
|
|
356
|
+
SPEECH_MODEL_TYPES.includes(modelType)) {
|
|
353
357
|
return undefined;
|
|
358
|
+
}
|
|
354
359
|
return `architecture "${modelType}" is not supported yet`;
|
|
355
360
|
}
|
|
356
361
|
/**
|
|
@@ -437,6 +442,8 @@ function toHubModel(entry, maxParams) {
|
|
|
437
442
|
model.gguf = true;
|
|
438
443
|
if (embedding)
|
|
439
444
|
model.embedding = true;
|
|
445
|
+
if (modelType !== undefined && SPEECH_MODEL_TYPES.includes(modelType))
|
|
446
|
+
model.speech = true;
|
|
440
447
|
if (architectures !== undefined)
|
|
441
448
|
model.architectures = architectures;
|
|
442
449
|
if (params !== undefined) {
|
|
@@ -546,7 +553,8 @@ export async function checkModel(repo, options = {}) {
|
|
|
546
553
|
hasEmbeddings = true;
|
|
547
554
|
}
|
|
548
555
|
}
|
|
549
|
-
|
|
556
|
+
const speech = modelType !== undefined && SPEECH_MODEL_TYPES.includes(modelType);
|
|
557
|
+
if (selected.weights.length > 0 && !hasEmbeddings && !encoder && !speech) {
|
|
550
558
|
reasons.push("unexpected weight layout (no model.embed_tokens.weight)");
|
|
551
559
|
}
|
|
552
560
|
const packed = packedWeightsReason(dtypes);
|
|
@@ -574,6 +582,8 @@ export async function checkModel(repo, options = {}) {
|
|
|
574
582
|
check.modelType = modelType;
|
|
575
583
|
if (embedding)
|
|
576
584
|
check.embedding = true;
|
|
585
|
+
if (speech)
|
|
586
|
+
check.speech = true;
|
|
577
587
|
if (config !== undefined) {
|
|
578
588
|
check.config = config;
|
|
579
589
|
if (shapes.length > 0) {
|
package/dist/index.d.ts
CHANGED
|
@@ -20,10 +20,11 @@ export { ask, DEFAULT_MAX_TOKENS, DEFAULT_MODEL, DEFAULT_TEMPERATURE, load, spli
|
|
|
20
20
|
export { DEFAULT_IMAGE_MODEL, encodePng, GeneratedImage, generateImage, ImageModel, loadImageModel, unloadImageModels, type GenerateImageOptions, type ImageGenerationOptions, type ImageModelInfo, type ImagePhase, type ImageProgress, type ImageQuant, type LoadImageModelOptions, } from "./image.js";
|
|
21
21
|
export { detectCapabilities, getWebGpuAdapterSummary, type Capabilities, type CapabilityEnvironment, type GpuAdapterLike, type GpuLike, type WebGpuAdapterSummary, } from "./capabilities.js";
|
|
22
22
|
export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session, type ModelFamily, } from "./models.js";
|
|
23
|
-
export type { Activations, AdapterMode, AdapterSource, ApplyAdapterOptions, Backend, ChatInputMessage, ChatMessage, ChatStream, ContentPart, GeneratedToken, CpuInfo, CompletionOptions, Device, EmbedOptions, Embeddings, EmbeddingInfo, FetchFile, FileData, FinishReason, GenerateOptions, GenerationConfig, GenerationResult, ImageInput, MediaOptions, MediaPart, MultimodalMessage, RawImage, VideoFrames, VideoInput, WeightCacheInfo, LoadedFile, LoadModelOptions, LoadProgress, LoraInfo, ModelInfo, ModelMemory, ModelSource, Pooling, Quant, ScoreOptions, ScoreOutput, StepOptions, } from "./types.js";
|
|
23
|
+
export type { Activations, AdapterMode, AdapterSource, AudioInput, ApplyAdapterOptions, Backend, ChatInputMessage, ChatMessage, ChatStream, ContentPart, GeneratedToken, CpuInfo, CompletionOptions, Device, EmbedOptions, Embeddings, EmbeddingInfo, FetchFile, FileData, FinishReason, GenerateOptions, GenerationConfig, GenerationResult, ImageInput, MediaOptions, MediaPart, MultimodalMessage, RawImage, VideoFrames, VideoInput, WeightCacheInfo, LoadedFile, LoadModelOptions, LoadProgress, LoraInfo, ModelInfo, ModelMemory, ModelSource, Pooling, Quant, ScoreOptions, ScoreOutput, SpeechInfo, StepOptions, TranscribeOptions, Transcription, TranscriptionSegment, } from "./types.js";
|
|
24
|
+
export { decodeAudio, SPEECH_SAMPLE_RATE } from "./audio.js";
|
|
24
25
|
export { WebslmError, type WebslmErrorCode } from "./errors.js";
|
|
25
26
|
export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, type CheckpointTraits, type CuratedModel, type SamplingDefaults, type SamplingSet, } from "./curated.js";
|
|
26
|
-
export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, ENCODER_MODEL_TYPES, isEmbeddingModel, formatParams, searchModels, SUPPORTED_MODEL_TYPES, type CheckModelOptions, type HubModel, type HubOptions, type ModelCheck, type SearchModelsOptions, } from "./hub.js";
|
|
27
|
+
export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, ENCODER_MODEL_TYPES, isEmbeddingModel, SPEECH_MODEL_TYPES, formatParams, searchModels, SUPPORTED_MODEL_TYPES, type CheckModelOptions, type HubModel, type HubOptions, type ModelCheck, type SearchModelsOptions, } from "./hub.js";
|
|
27
28
|
export { cacheUsage, deleteCachedModel, listCachedModels, type CacheOptions, type CachedModel, type CachedRevision, type CacheUsage, } from "./cache-management.js";
|
|
28
29
|
export type { Dtype, SafetensorsHeader, TensorInfo } from "./safetensors.js";
|
|
29
30
|
export { selectWasmFlavour, supportsRelaxedSimd, supportsWasmThreads, type FlavourEnvironment, type WasmFlavour, } from "./wasm-flavour.js";
|
package/dist/index.js
CHANGED
|
@@ -20,9 +20,10 @@ export { ask, DEFAULT_MAX_TOKENS, DEFAULT_MODEL, DEFAULT_TEMPERATURE, load, spli
|
|
|
20
20
|
export { DEFAULT_IMAGE_MODEL, encodePng, GeneratedImage, generateImage, ImageModel, loadImageModel, unloadImageModels, } from "./image.js";
|
|
21
21
|
export { detectCapabilities, getWebGpuAdapterSummary, } from "./capabilities.js";
|
|
22
22
|
export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session, } from "./models.js";
|
|
23
|
+
export { decodeAudio, SPEECH_SAMPLE_RATE } from "./audio.js";
|
|
23
24
|
export { WebslmError } from "./errors.js";
|
|
24
25
|
export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, } from "./curated.js";
|
|
25
|
-
export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, ENCODER_MODEL_TYPES, isEmbeddingModel, formatParams, searchModels, SUPPORTED_MODEL_TYPES, } from "./hub.js";
|
|
26
|
+
export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, ENCODER_MODEL_TYPES, isEmbeddingModel, SPEECH_MODEL_TYPES, formatParams, searchModels, SUPPORTED_MODEL_TYPES, } from "./hub.js";
|
|
26
27
|
export { cacheUsage, deleteCachedModel, listCachedModels, } from "./cache-management.js";
|
|
27
28
|
export { selectWasmFlavour, supportsRelaxedSimd, supportsWasmThreads, } from "./wasm-flavour.js";
|
|
28
29
|
export { loadWasm } from "./wasm.js";
|
package/dist/models.d.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { EngineClient } from "./client.js";
|
|
3
3
|
import { type CheckpointTraits } from "./curated.js";
|
|
4
4
|
import type { WireSource } from "./protocol.js";
|
|
5
|
-
import type { AdapterSource, Backend, ApplyAdapterOptions, ChatInputMessage, ChatStream, CompletionOptions, Device, EmbedOptions, Embeddings, FetchFile, GenerateOptions, LoadModelOptions, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions } from "./types.js";
|
|
5
|
+
import type { AdapterSource, Backend, ApplyAdapterOptions, AudioInput, ChatInputMessage, ChatStream, CompletionOptions, Device, EmbedOptions, Embeddings, FetchFile, GenerateOptions, LoadModelOptions, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions, TranscribeOptions, Transcription } from "./types.js";
|
|
6
6
|
/**
|
|
7
7
|
* An engine (a worker, or the calling thread) that several models can share
|
|
8
8
|
* (see {@link LoadModelOptions.engine}): one WebAssembly instance, its memory
|
|
@@ -211,6 +211,24 @@ export declare class Model extends Conversation {
|
|
|
211
211
|
* ```
|
|
212
212
|
*/
|
|
213
213
|
embed(texts: string | readonly string[], options?: EmbedOptions): Promise<Embeddings>;
|
|
214
|
+
/**
|
|
215
|
+
* Transcribes speech with a speech recognition model (Whisper; see
|
|
216
|
+
* {@link ModelInfo.speech}), 30 s at a time, decoding greedily as
|
|
217
|
+
* `transformers` does. `audio` is mono PCM (`Float32Array`, at
|
|
218
|
+
* `options.sampleRate`, 16 kHz by default) or an audio file: WAV
|
|
219
|
+
* everywhere, any format the browser decodes in a page (see
|
|
220
|
+
* {@link AudioInput}). The language is detected unless given;
|
|
221
|
+
* `task: "translate"` translates into English. Rejects with
|
|
222
|
+
* `UNSUPPORTED_TASK` on other models, and with `ABORTED` when
|
|
223
|
+
* `options.signal` fires.
|
|
224
|
+
*
|
|
225
|
+
* ```ts
|
|
226
|
+
* const model = await loadModel("openai/whisper-tiny");
|
|
227
|
+
* const file = await fetch("/speech.mp3").then((r) => r.blob());
|
|
228
|
+
* const { text, language } = await model.transcribe(file, { onToken: (t) => output.append(t) });
|
|
229
|
+
* ```
|
|
230
|
+
*/
|
|
231
|
+
transcribe(audio: AudioInput, options?: TranscribeOptions): Promise<Transcription>;
|
|
214
232
|
/** Starts an independent session (its own KV cache) for low-level use. */
|
|
215
233
|
session(): Promise<Session>;
|
|
216
234
|
/**
|