webslm 0.7.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.
Files changed (45) hide show
  1. package/README.md +116 -2
  2. package/dist/ai-sdk/embedding-model.d.ts +52 -0
  3. package/dist/ai-sdk/embedding-model.js +112 -0
  4. package/dist/ai-sdk/image-model.d.ts +53 -0
  5. package/dist/ai-sdk/image-model.js +148 -0
  6. package/dist/ai-sdk/index.d.ts +54 -0
  7. package/dist/ai-sdk/index.js +85 -11
  8. package/dist/ai-sdk/transcription-model.d.ts +48 -0
  9. package/dist/ai-sdk/transcription-model.js +115 -0
  10. package/dist/audio.d.ts +33 -0
  11. package/dist/audio.js +87 -0
  12. package/dist/client.d.ts +6 -0
  13. package/dist/client.js +8 -1
  14. package/dist/download.js +2 -2
  15. package/dist/engine.js +233 -0
  16. package/dist/errors.d.ts +5 -0
  17. package/dist/errors.js +1 -0
  18. package/dist/hub.d.ts +47 -3
  19. package/dist/hub.js +97 -8
  20. package/dist/image.d.ts +201 -0
  21. package/dist/image.js +353 -0
  22. package/dist/index.d.ts +6 -3
  23. package/dist/index.js +5 -2
  24. package/dist/models.d.ts +37 -1
  25. package/dist/models.js +99 -6
  26. package/dist/native.d.ts +34 -0
  27. package/dist/protocol.d.ts +106 -2
  28. package/dist/simple.d.ts +4 -1
  29. package/dist/simple.js +9 -2
  30. package/dist/types.d.ts +107 -1
  31. package/dist/wasm.d.ts +4 -0
  32. package/native-manifest.json +29 -29
  33. package/package.json +1 -1
  34. package/wasm/relaxed/webslm_wasm.d.ts +97 -6
  35. package/wasm/relaxed/webslm_wasm.js +223 -18
  36. package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
  37. package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +13 -3
  38. package/wasm/simd/webslm_wasm.d.ts +97 -6
  39. package/wasm/simd/webslm_wasm.js +223 -18
  40. package/wasm/simd/webslm_wasm_bg.wasm +0 -0
  41. package/wasm/simd/webslm_wasm_bg.wasm.d.ts +13 -3
  42. package/wasm/threads/webslm_wasm.d.ts +98 -7
  43. package/wasm/threads/webslm_wasm.js +228 -23
  44. package/wasm/threads/webslm_wasm_bg.wasm +0 -0
  45. package/wasm/threads/webslm_wasm_bg.wasm.d.ts +14 -4
@@ -13,21 +13,68 @@
13
13
  * });
14
14
  * ```
15
15
  *
16
+ * Encoders (BERT, ModernBERT, model2vec) are embedding models, behind
17
+ * `embed` and `embedMany`:
18
+ *
19
+ * ```ts
20
+ * import { embedMany } from "ai";
21
+ *
22
+ * const { embeddings } = await embedMany({
23
+ * model: webslm.embeddingModel("sentence-transformers/all-MiniLM-L6-v2"),
24
+ * values: ["sunny day at the beach", "rainy afternoon in the city"],
25
+ * });
26
+ * ```
27
+ *
28
+ * Text-to-image models come from `webslm.imageModel(id)`, for the AI SDK's
29
+ * `generateImage`:
30
+ *
31
+ * ```ts
32
+ * import { generateImage } from "ai";
33
+ *
34
+ * const { image } = await generateImage({
35
+ * model: webslm.imageModel("IDKiro/sdxs-512-dreamshaper"),
36
+ * prompt: "a lighthouse at dusk",
37
+ * seed: 42,
38
+ * });
39
+ * ```
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
+ *
16
52
  * `ai` (v7) and `@ai-sdk/provider` (v4) are optional peer dependencies of
17
53
  * `webslm`: install them to use this entry point.
18
54
  *
19
55
  * @packageDocumentation
20
56
  */
21
57
  import { WebslmError } from "../errors.js";
58
+ import { loadImageModel } from "../image.js";
22
59
  import { loadModel } from "../models.js";
60
+ import { EMBEDDING_SETTING_KEYS, WebslmEmbeddingModel, } from "./embedding-model.js";
61
+ import { ImageModelSlot, WebslmImageModel, } from "./image-model.js";
23
62
  import { CALL_SETTING_KEYS, WebslmLanguageModel } from "./language-model.js";
63
+ import { TRANSCRIPTION_SETTING_KEYS, WebslmTranscriptionModel, } from "./transcription-model.js";
24
64
  import { ModelSlot, pickLoadOptions, slotKey, } from "./loader.js";
25
65
  export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, } from "../curated.js";
26
66
  export { searchModels } from "../hub.js";
27
67
  export { DEFAULT_MODEL } from "../simple.js";
28
68
  export { WebslmLanguageModel, } from "./language-model.js";
29
- function unsupportedModel(kind) {
30
- throw new WebslmError("INVALID_ARGUMENT", `webslm provides language models only, not ${kind} models`);
69
+ export { WebslmEmbeddingModel, } from "./embedding-model.js";
70
+ export { WebslmTranscriptionModel, } from "./transcription-model.js";
71
+ export { MAX_IMAGES_PER_CALL, WebslmImageModel, } from "./image-model.js";
72
+ export { DEFAULT_IMAGE_MODEL } from "../image.js";
73
+ function checkModelId(modelId) {
74
+ if (typeof modelId !== "string" || modelId.trim() === "") {
75
+ throw new WebslmError("INVALID_ARGUMENT", "the model id must be a Hugging Face repository id");
76
+ }
77
+ return modelId.trim();
31
78
  }
32
79
  /**
33
80
  * Creates a provider with its own load options and model cache.
@@ -42,29 +89,56 @@ function unsupportedModel(kind) {
42
89
  export function createWebslm(options = {}) {
43
90
  const engine = options.engine ?? { loadModel };
44
91
  const slots = new Map();
45
- const languageModel = (modelId, settings = {}) => {
46
- if (typeof modelId !== "string" || modelId.trim() === "") {
47
- throw new WebslmError("INVALID_ARGUMENT", "the model id must be a Hugging Face repository id");
92
+ const imageEngine = options.imageEngine ?? { loadImageModel };
93
+ const imageSlots = new Map();
94
+ const imageModel = (modelId, settings = {}) => {
95
+ const id = checkModelId(modelId);
96
+ const { steps: _steps, guidance: _guidance, negativePrompt: _negative, onProgress, ...load } = settings;
97
+ void _steps;
98
+ void _guidance;
99
+ void _negative;
100
+ const key = JSON.stringify([id, Object.entries(load).sort(([a], [b]) => a.localeCompare(b))]);
101
+ let slot = imageSlots.get(key);
102
+ if (slot === undefined) {
103
+ slot = new ImageModelSlot(imageEngine, id, { ...load, ...(onProgress === undefined ? {} : { onProgress }) });
104
+ imageSlots.set(key, slot);
48
105
  }
49
- const id = modelId.trim();
50
- const loadOptions = { ...options.loadOptions, ...pickLoadOptions(settings, CALL_SETTING_KEYS) };
106
+ return new WebslmImageModel(id, slot, settings);
107
+ };
108
+ const slotFor = (id, loadOptions) => {
51
109
  const key = slotKey(id, loadOptions);
52
110
  let slot = slots.get(key);
53
111
  if (slot === undefined) {
54
112
  slot = new ModelSlot(engine, id, loadOptions);
55
113
  slots.set(key, slot);
56
114
  }
57
- return new WebslmLanguageModel(id, slot, settings);
115
+ return slot;
116
+ };
117
+ const languageModel = (modelId, settings = {}) => {
118
+ const id = checkModelId(modelId);
119
+ const loadOptions = { ...options.loadOptions, ...pickLoadOptions(settings, CALL_SETTING_KEYS) };
120
+ return new WebslmLanguageModel(id, slotFor(id, loadOptions), settings);
121
+ };
122
+ const embeddingModel = (modelId, settings = {}) => {
123
+ const id = checkModelId(modelId);
124
+ const loadOptions = { ...options.loadOptions, ...pickLoadOptions(settings, EMBEDDING_SETTING_KEYS) };
125
+ return new WebslmEmbeddingModel(id, slotFor(id, loadOptions), settings);
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);
58
131
  };
59
132
  const provider = (modelId, settings) => languageModel(modelId, settings);
60
133
  return Object.assign(provider, {
61
134
  specificationVersion: "v4",
62
135
  languageModel,
63
- embeddingModel: () => unsupportedModel("embedding"),
64
- imageModel: () => unsupportedModel("image"),
136
+ embeddingModel,
137
+ imageModel,
138
+ transcriptionModel,
65
139
  unloadAll: async () => {
66
140
  const all = [...slots.values()];
67
- await Promise.all(all.map((slot) => slot.unload()));
141
+ await Promise.all([...all.map((slot) => slot.unload()), ...[...imageSlots.values()].map((slot) => slot.unload())]);
68
142
  },
69
143
  });
70
144
  }
@@ -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
+ }
@@ -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/client.d.ts CHANGED
@@ -35,6 +35,12 @@ export interface RequestHooks {
35
35
  readonly onRead?: FetchFile;
36
36
  /** Serves reads of a `fetch` LoRA adapter source. */
37
37
  readonly onAdapterRead?: FetchFile;
38
+ /** Serves reads of a `fetch` image decoder source. */
39
+ readonly onDecoderRead?: FetchFile;
40
+ /** Progress of an image generation. */
41
+ readonly onImageProgress?: (progress: Extract<Response, {
42
+ type: "imageProgress";
43
+ }>) => void;
38
44
  readonly signal?: AbortSignal;
39
45
  readonly transfer?: Transferable[];
40
46
  }
package/dist/client.js CHANGED
@@ -87,8 +87,15 @@ export class EngineClient {
87
87
  case "prefill":
88
88
  pending.hooks.onPrefill?.(message.done, message.total);
89
89
  break;
90
+ case "imageProgress":
91
+ pending.hooks.onImageProgress?.(message);
92
+ break;
90
93
  case "read":
91
- void this.#serveRead(message.target === "adapter" ? pending.hooks.onAdapterRead : pending.hooks.onRead, message);
94
+ void this.#serveRead(message.target === "adapter"
95
+ ? pending.hooks.onAdapterRead
96
+ : message.target === "decoder"
97
+ ? pending.hooks.onDecoderRead
98
+ : pending.hooks.onRead, message);
92
99
  break;
93
100
  }
94
101
  }
package/dist/download.js CHANGED
@@ -14,7 +14,7 @@
14
14
  */
15
15
  import { checkRepoId, filePath, readCliManifest, readManifest, readRef, writeCliManifest, writeManifest, writeRef, } from "./cache/models.js";
16
16
  import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
17
- import { SAFETENSORS_INDEX, fetchRevision, fileUrl, hubFetch, isAdapterListing, isGgufFile, selectCheckpointFiles, } from "./hub.js";
17
+ import { SAFETENSORS_INDEX, fetchRevision, fileUrl, hubFetch, isAdapterListing, isGgufFile, isImagePipelineListing, selectCheckpointFiles, } from "./hub.js";
18
18
  const SHA_PATTERN = /^[0-9a-f]{40}$/;
19
19
  /** Makes `repo@revision` available in `options.store` and returns a reader over it. */
20
20
  export async function prepareHubCheckpoint(repoId, revision, options) {
@@ -91,7 +91,7 @@ export async function prepareHubCheckpoint(repoId, revision, options) {
91
91
  : `${repo}@${rev} has no ${options.file}`);
92
92
  }
93
93
  const ggufWeights = selected.weights.some(isGgufFile);
94
- if (!names.includes("config.json") && !isAdapterListing(names) && !ggufWeights) {
94
+ if (!names.includes("config.json") && !isAdapterListing(names) && !isImagePipelineListing(names) && !ggufWeights) {
95
95
  throw new WebslmError("INVALID_CHECKPOINT", `${repo}@${rev} has no config.json`);
96
96
  }
97
97
  const files = [...selected.side, ...(selected.index ? [selected.index] : []), ...selected.weights];