@tanstack-ai-browser/onnx 0.0.0-stage → 0.3.3

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 daveycodez
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,70 @@
1
- # Temporary Holding Version
1
+ # @tanstack-ai-browser/onnx
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [TanStack AI](https://tanstack.com/ai) image adapter for ONNX models in the browser, on [ONNX Runtime Web](https://www.npmjs.com/package/onnxruntime-web) (1.31.1): WebGPU where the browser has a GPU adapter, else the CPU (WebAssembly). It runs the official package, unmodified, through its public API.
4
+
5
+ The model today is [Tessera-small](https://huggingface.co/thejagstudio/tessera-small), which draws 16×16 pixel-art sprites from text, in [cfahlgren1's int8 ONNX build](https://huggingface.co/cfahlgren1/tessera-small-onnx) (115 MB).
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @tanstack-ai-browser/onnx @tanstack/ai
11
+ ```
12
+
13
+ ## Use
14
+
15
+ ```ts
16
+ import { generateImage } from "@tanstack/ai"
17
+ import { onnxImage } from "@tanstack-ai-browser/onnx"
18
+
19
+ const result = await generateImage({
20
+ adapter: onnxImage("cfahlgren1/tessera-small-onnx"),
21
+ prompt: "cat wearing sunglasses",
22
+ numberOfImages: 4,
23
+ threadId
24
+ })
25
+
26
+ for (const image of result.images) {
27
+ const img = document.createElement("img")
28
+ img.src = `data:image/png;base64,${image.b64Json}`
29
+ img.style.imageRendering = "pixelated"
30
+ document.body.append(img)
31
+ }
32
+ ```
33
+
34
+ Each image is a 16×16 PNG (`b64Json`), with transparency. Scale it up with `image-rendering: pixelated` to keep its pixels sharp.
35
+
36
+ - `numberOfImages`: 1 to 8 (default 1). They're drawn together in one batch.
37
+ - `size`: the model's own, `"16x16"`, or left out.
38
+ - `prompt`: text, best as a short phrase. The CLIP text encoder reads 24 tokens. Image parts are refused.
39
+ - `modelOptions`: `seed` (the same seed, prompt and settings draw the same images; random if left out), `steps` (default 16; fewer is faster and rougher) and `guidanceScale` (default 3).
40
+
41
+ ## Loading
42
+
43
+ ```ts
44
+ const adapter = onnxImage("cfahlgren1/tessera-small-onnx", {
45
+ onDownloadProgress: (progress) => console.log(progress)
46
+ })
47
+ if ((await adapter.availability()) !== "unavailable") await adapter.create()
48
+ ```
49
+
50
+ - `availability()`: `"available"` once the model's files are stored (or it's loaded), `"downloading"` while this adapter downloads them, `"downloadable"` otherwise, and `"unavailable"` without WebAssembly.
51
+ - `create()`: downloads the files where they aren't stored, with progress from 0 to 1, and loads the model. `generateImage()` doesn't need it: the first call loads the model too.
52
+ - `backend()`: `"webgpu"` or `"wasm"`, once loaded.
53
+ - `destroy()` unloads the model and keeps its files. `remove()` deletes the files too.
54
+
55
+ The files are pinned to a commit and kept in the page's Cache Storage (`tanstack-ai-browser-onnx`). One model is loaded at a time: loading another unloads the first.
56
+
57
+ ### Backends
58
+
59
+ - **WebGPU** where `navigator.gpu` gives an adapter. If the GPU can't load the model, it falls back to the CPU.
60
+ - **WebAssembly** everywhere else. ONNX Runtime's WebAssembly files load from jsDelivr at the installed version. Pass `wasmPaths` to serve them yourself.
61
+ - **Not WebGL.** ONNX Runtime's WebGL backend can't run these models: it has no int8 dequantization, among other ops.
62
+ - `backend: "webgpu" | "wasm"` forces one.
63
+ - `sessionOptions` and `webgpuOptions` pass ONNX Runtime session options and WebGPU backend options (such as `storageBufferCacheMode`) over the adapter's own.
64
+ - **Memory on iPhone Safari:** ONNX Runtime 1.31's WebGPU backend held about 1.5 GB there for one Tessera sprite, and four crashed the tab (about 2 GB limit). Its CPU backend held about 620 MB for four. In Chrome its WebGPU buffers were about 160 MB. webgllm's image adapter (`webgllmImage` in `@tanstack-ai-browser/webgllm`) held about 380 MB on WebGPU for one sprite, measured on an iPad Pro.
65
+
66
+ Constant folding is off when a model loads. Otherwise ONNX Runtime turns every int8 weight into a float32 copy, about four times the memory, which is more than a phone gives a tab. The weights are dequantized as they're used instead.
67
+
68
+ ## License
69
+
70
+ The package is MIT. **Tessera-small is [CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/), by Jagrat Patel (TheJagStudio): no commercial use of the model or the images it draws** without a license from its author. The CLIP text encoder is OpenAI's (MIT). The sampler follows Tessera's published one.
@@ -0,0 +1,80 @@
1
+ import type { ImageGenerationOptions, ImageGenerationResult } from "@tanstack/ai";
2
+ import { BaseImageAdapter } from "@tanstack/ai/adapters";
3
+ import type { InferenceSession } from "onnxruntime-web";
4
+ import type { OnnxImageModel, OnnxImageModelSizeByName } from "./model-meta.js";
5
+ import type { OnnxBackend } from "./runtime.js";
6
+ /** Download progress, 0 to 1 (1 once the model is loaded). */
7
+ export type DownloadProgressCallback = (progress: number) => void;
8
+ /** Where a model stands on this device. */
9
+ export type Availability = "unavailable" | "downloadable" | "downloading" | "available";
10
+ export type OnnxImageConfig = {
11
+ /** Called with every model download's progress, 0 to 1. */
12
+ onDownloadProgress?: DownloadProgressCallback;
13
+ /** Where ONNX Runtime's WebAssembly files load from (default: jsDelivr, at the installed version). */
14
+ wasmPaths?: string;
15
+ /** Run on this backend instead of the best one the browser has. */
16
+ backend?: OnnxBackend;
17
+ /** ONNX Runtime session options, over the adapter's own (see runtime.ts's `createSessions`). */
18
+ sessionOptions?: InferenceSession.SessionOptions;
19
+ /** ONNX Runtime WebGPU backend options (such as `storageBufferCacheMode`), on WebGPU. */
20
+ webgpuOptions?: Record<string, unknown>;
21
+ };
22
+ /** Sampler settings, per call (`modelOptions`). */
23
+ export type OnnxImageProviderOptions = {
24
+ /** The random seed: the same seed, prompt and settings draw the same images. Random if left out. */
25
+ seed?: number;
26
+ /** Denoiser passes (default 16). Fewer is faster and rougher. */
27
+ steps?: number;
28
+ /** Classifier-free guidance (default 3): how strongly the images follow the prompt. */
29
+ guidanceScale?: number;
30
+ };
31
+ /** Most images one call draws (each is two rows of the denoiser's batch). */
32
+ export declare const MAX_IMAGES = 8;
33
+ export declare class OnnxImageAdapter<TModel extends OnnxImageModel> extends BaseImageAdapter<TModel, OnnxImageProviderOptions, Record<OnnxImageModel, OnnxImageProviderOptions>, OnnxImageModelSizeByName> {
34
+ readonly name: "onnx";
35
+ private readonly meta;
36
+ private readonly settings;
37
+ /** Downloads of this adapter's model going on now. */
38
+ private downloading;
39
+ constructor(model: TModel, config?: OnnxImageConfig);
40
+ /** What the page's sessions are made for: the model and every setting that changes them. */
41
+ private get key();
42
+ /** The backend the model runs on, once it's loaded here. */
43
+ backend(): Promise<OnnxBackend | undefined>;
44
+ /**
45
+ * Where the model stands here: "unavailable" without WebAssembly;
46
+ * "available" once its files are stored (or it's loaded); "downloading"
47
+ * while this adapter downloads it; else "downloadable" (it downloads at
48
+ * `create`, or at the first `generateImage()`).
49
+ */
50
+ availability(): Promise<Availability>;
51
+ /**
52
+ * Downloads the model if it isn't stored and loads it, with the download's
53
+ * progress, 0 to 1, then 1 once it's ready. Resolves to this adapter.
54
+ * `generateImage()` doesn't need it: the first call loads the model too.
55
+ * Loading another model first unloads the page's current one.
56
+ */
57
+ create(options?: {
58
+ onDownloadProgress?: DownloadProgressCallback;
59
+ signal?: AbortSignal;
60
+ }): Promise<this>;
61
+ /** Unloads the model, if it's the page's, after the drawings queued before. Its stored files stay. */
62
+ destroy(): Promise<void>;
63
+ /** Removes the model's stored files, after unloading it. Returns whether any were stored. */
64
+ remove(): Promise<boolean>;
65
+ /** (In the lifecycle queue.) */
66
+ private unloadNow;
67
+ /**
68
+ * (In the lifecycle queue.) The page's sessions for this adapter's model
69
+ * and settings: the ones loaded, or new ones after the page's others are
70
+ * released.
71
+ */
72
+ private load;
73
+ private loadFresh;
74
+ generateImages(options: ImageGenerationOptions<OnnxImageProviderOptions, OnnxImageModelSizeByName[TModel]>): Promise<ImageGenerationResult>;
75
+ }
76
+ /** Most denoising steps one call takes. */
77
+ export declare const MAX_STEPS = 1000;
78
+ /** An image adapter for one of the catalog's ONNX models. */
79
+ export declare function onnxImage<TModel extends OnnxImageModel>(model: TModel, config?: OnnxImageConfig): OnnxImageAdapter<TModel>;
80
+ //# sourceMappingURL=adapter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EACV,sBAAsB,EACtB,qBAAqB,EACtB,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AACxD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAA;AAGvD,OAAO,KAAK,EACV,cAAc,EAEd,wBAAwB,EACzB,MAAM,iBAAiB,CAAA;AAQxB,OAAO,KAAK,EAAE,WAAW,EAAO,MAAM,cAAc,CAAA;AAWpD,8DAA8D;AAC9D,MAAM,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,OAAO,IAAI,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC,CAGhD;IAED;;;;;OAKG;IACG,YAAY,IAAI,OAAO,CAAC,YAAY,CAAC,CAO1C;IAED;;;;;OAKG;IACH,MAAM,CACJ,OAAO,GAAE;QACP,kBAAkB,CAAC,EAAE,wBAAwB,CAAA;QAC7C,MAAM,CAAC,EAAE,WAAW,CAAA;KAChB,GACL,OAAO,CAAC,IAAI,CAAC,CAQf;IAED,sGAAsG;IACtG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAEvB;IAED,6FAA6F;IAC7F,MAAM,IAAI,OAAO,CAAC,OAAO,CAAC,CAKzB;IAED,gCAAgC;YAClB,SAAS;IAOvB;;;;OAIG;YACW,IAAI;YAqBJ,SAAS;IA4FjB,cAAc,CAClB,OAAO,EAAE,sBAAsB,CAC7B,wBAAwB,EACxB,wBAAwB,CAAC,MAAM,CAAC,CACjC,GACA,OAAO,CAAC,qBAAqB,CAAC,CA8DhC;CACF;AAED,2CAA2C;AAC3C,eAAO,MAAM,SAAS,OAAO,CAAA;AA4B7B,6DAA6D;AAC7D,wBAAgB,SAAS,CAAC,MAAM,SAAS,cAAc,EACrD,KAAK,EAAE,MAAM,EACb,MAAM,GAAE,eAAoB,GAC3B,gBAAgB,CAAC,MAAM,CAAC,CAE1B"}
@@ -0,0 +1,297 @@
1
+ /**
2
+ * TanStack AI's image adapter for ONNX models in the browser, on ONNX
3
+ * Runtime Web: WebGPU where the browser has a GPU adapter, else the CPU
4
+ * (WebAssembly). `generateImage({ adapter: onnxImage(model), prompt })`.
5
+ */
6
+ import { Tokenizer } from "@huggingface/tokenizers";
7
+ import { BaseImageAdapter } from "@tanstack/ai/adapters";
8
+ import { fileUrl, ONNX_MODEL_META } from "./model-meta.js";
9
+ import { encodePng, toBase64 } from "./png.js";
10
+ import { createSessions, DEFAULT_WASM_PATHS, hasWebGpu, loadOrt } from "./runtime.js";
11
+ import { serial } from "./lifecycle.js";
12
+ import { allStored, fileBytes, removeFiles } from "./storage.js";
13
+ import { DEFAULT_SAMPLER, drawSprites, fixedLengthIds, GRID, spritePixels } from "./tessera.js";
14
+ /** Most images one call draws (each is two rows of the denoiser's batch). */
15
+ export const MAX_IMAGES = 8;
16
+ /**
17
+ * The page's loaded model: one at a time, so two never sit in memory
18
+ * together. Only tasks in the lifecycle queue (lifecycle.ts) change it.
19
+ */
20
+ let current;
21
+ /** A stable id for a value JSON can't stand for (a GPUDevice in webgpuOptions, say), by identity. */
22
+ const identities = new WeakMap();
23
+ let nextIdentity = 0;
24
+ const settingsKey = (value) => JSON.stringify(value ?? null, (_key, v) => {
25
+ const plain = typeof v !== "object" ||
26
+ v === null ||
27
+ Array.isArray(v) ||
28
+ Object.getPrototypeOf(v) === Object.prototype;
29
+ if (typeof v === "function" || !plain) {
30
+ const object = v;
31
+ if (!identities.has(object))
32
+ identities.set(object, ++nextIdentity);
33
+ return `#${identities.get(object)}`;
34
+ }
35
+ return v;
36
+ });
37
+ async function release(entry) {
38
+ const loaded = await entry.ready.catch(() => undefined);
39
+ if (loaded)
40
+ await Promise.all([loaded.denoiser.release(), loaded.textEncoder.release()]);
41
+ }
42
+ const modelUrls = (meta) => Object.values(meta.files).map((file) => fileUrl(meta, file));
43
+ /** The prompt's text: a string, or its text parts. Image-conditioned prompts aren't supported. */
44
+ function promptText(prompt) {
45
+ if (typeof prompt === "string")
46
+ return prompt;
47
+ return prompt
48
+ .map((part) => {
49
+ if (part.type !== "text")
50
+ throw new Error(`onnxImage only takes text prompts, not ${part.type} parts`);
51
+ return part.content;
52
+ })
53
+ .join(" ");
54
+ }
55
+ export class OnnxImageAdapter extends BaseImageAdapter {
56
+ name = "onnx";
57
+ meta;
58
+ settings;
59
+ /** Downloads of this adapter's model going on now. */
60
+ downloading = 0;
61
+ constructor(model, config = {}) {
62
+ super(model, {});
63
+ const meta = ONNX_MODEL_META[model];
64
+ if (!meta)
65
+ throw new Error(`onnxImage doesn't know ${model}`);
66
+ this.meta = meta;
67
+ this.settings = config;
68
+ }
69
+ /** What the page's sessions are made for: the model and every setting that changes them. */
70
+ get key() {
71
+ const { backend, wasmPaths, sessionOptions, webgpuOptions } = this.settings;
72
+ return JSON.stringify([
73
+ this.model,
74
+ backend ?? null,
75
+ wasmPaths ?? null,
76
+ settingsKey(sessionOptions),
77
+ settingsKey(webgpuOptions)
78
+ ]);
79
+ }
80
+ /** The backend the model runs on, once it's loaded here. */
81
+ async backend() {
82
+ if (current?.key !== this.key)
83
+ return undefined;
84
+ return (await current.ready.catch(() => undefined))?.backend;
85
+ }
86
+ /**
87
+ * Where the model stands here: "unavailable" without WebAssembly;
88
+ * "available" once its files are stored (or it's loaded); "downloading"
89
+ * while this adapter downloads it; else "downloadable" (it downloads at
90
+ * `create`, or at the first `generateImage()`).
91
+ */
92
+ async availability() {
93
+ if (typeof WebAssembly === "undefined")
94
+ return "unavailable";
95
+ if (current?.key === this.key)
96
+ return "available";
97
+ if (this.downloading > 0)
98
+ return "downloading";
99
+ return (await allStored(modelUrls(this.meta)))
100
+ ? "available"
101
+ : "downloadable";
102
+ }
103
+ /**
104
+ * Downloads the model if it isn't stored and loads it, with the download's
105
+ * progress, 0 to 1, then 1 once it's ready. Resolves to this adapter.
106
+ * `generateImage()` doesn't need it: the first call loads the model too.
107
+ * Loading another model first unloads the page's current one.
108
+ */
109
+ create(options = {}) {
110
+ const ready = serial(() => this.load(options), options.signal).then(() => {
111
+ options.onDownloadProgress?.(1);
112
+ this.settings.onDownloadProgress?.(1);
113
+ return this;
114
+ });
115
+ ready.catch(() => undefined);
116
+ return ready;
117
+ }
118
+ /** Unloads the model, if it's the page's, after the drawings queued before. Its stored files stay. */
119
+ destroy() {
120
+ return serial(() => this.unloadNow());
121
+ }
122
+ /** Removes the model's stored files, after unloading it. Returns whether any were stored. */
123
+ remove() {
124
+ return serial(async () => {
125
+ await this.unloadNow();
126
+ return removeFiles(modelUrls(this.meta));
127
+ });
128
+ }
129
+ /** (In the lifecycle queue.) */
130
+ async unloadNow() {
131
+ if (current?.key !== this.key)
132
+ return;
133
+ const entry = current;
134
+ current = undefined;
135
+ await release(entry);
136
+ }
137
+ /**
138
+ * (In the lifecycle queue.) The page's sessions for this adapter's model
139
+ * and settings: the ones loaded, or new ones after the page's others are
140
+ * released.
141
+ */
142
+ async load(options = {}) {
143
+ if (current?.key === this.key)
144
+ return current.ready;
145
+ if (current) {
146
+ const previous = current;
147
+ current = undefined;
148
+ await release(previous);
149
+ }
150
+ const ready = this.loadFresh(options);
151
+ const entry = { key: this.key, ready };
152
+ current = entry;
153
+ ready.catch(() => {
154
+ if (current === entry)
155
+ current = undefined;
156
+ });
157
+ return ready;
158
+ }
159
+ async loadFresh(options) {
160
+ const { meta } = this;
161
+ const { files } = meta;
162
+ const stored = await allStored(modelUrls(meta));
163
+ const total = files.denoiser.bytes + files.textEncoder.bytes;
164
+ const seen = { denoiser: 0, textEncoder: 0 };
165
+ const report = () => {
166
+ const progress = Math.min((seen.denoiser + seen.textEncoder) / total, 0.999);
167
+ options.onDownloadProgress?.(progress);
168
+ this.settings.onDownloadProgress?.(progress);
169
+ };
170
+ const signal = options.signal;
171
+ signal?.throwIfAborted();
172
+ if (!stored)
173
+ this.downloading++;
174
+ let bytes;
175
+ try {
176
+ bytes = await Promise.all([
177
+ fileBytes(fileUrl(meta, files.denoiser), {
178
+ signal,
179
+ onBytes: (n) => ((seen.denoiser = n), report())
180
+ }),
181
+ fileBytes(fileUrl(meta, files.textEncoder), {
182
+ signal,
183
+ onBytes: (n) => ((seen.textEncoder = n), report())
184
+ }),
185
+ fileBytes(fileUrl(meta, files.tokenizer), { signal }),
186
+ fileBytes(fileUrl(meta, files.palette), { signal })
187
+ ]);
188
+ }
189
+ finally {
190
+ if (!stored)
191
+ this.downloading--;
192
+ }
193
+ const [denoiserBytes, textEncoderBytes, tokenizerBytes, paletteBytes] = bytes;
194
+ const decode = (b) => JSON.parse(new TextDecoder().decode(b));
195
+ const tokenizer = new Tokenizer(decode(tokenizerBytes), {});
196
+ const palette = decode(paletteBytes).palette_rgba;
197
+ const endToken = tokenizer.token_to_id("<|endoftext|>");
198
+ if (endToken === undefined)
199
+ throw new Error(`${this.model}'s tokenizer has no <|endoftext|> token`);
200
+ const ort = await loadOrt(this.settings.wasmPaths ?? DEFAULT_WASM_PATHS);
201
+ // Cached files come back whatever the signal says: a caller that stopped meanwhile makes no sessions.
202
+ signal?.throwIfAborted();
203
+ const files_ = { denoiser: denoiserBytes, textEncoder: textEncoderBytes };
204
+ let backend = this.settings.backend ?? ((await hasWebGpu()) ? "webgpu" : "wasm");
205
+ let sessions;
206
+ const extra = this.settings.sessionOptions;
207
+ try {
208
+ sessions = await createSessions(ort, files_, backend, extra, this.settings.webgpuOptions);
209
+ }
210
+ catch (error) {
211
+ // A GPU that can't take the model: the CPU still can (unless asked for WebGPU).
212
+ if (backend !== "webgpu" || this.settings.backend)
213
+ throw error;
214
+ console.warn("onnxImage: WebGPU couldn't load the model, running it on the CPU", error);
215
+ backend = "wasm";
216
+ sessions = await createSessions(ort, files_, backend, extra, this.settings.webgpuOptions);
217
+ }
218
+ return {
219
+ model: this.model,
220
+ backend,
221
+ ort,
222
+ ...sessions,
223
+ tokenizer,
224
+ endToken,
225
+ palette
226
+ };
227
+ }
228
+ async generateImages(options) {
229
+ const { logger, abortSignal, modelOptions = {} } = options;
230
+ const count = options.numberOfImages ?? 1;
231
+ try {
232
+ if (!Number.isInteger(count) || count < 1 || count > MAX_IMAGES) {
233
+ throw new Error(`numberOfImages must be 1 to ${MAX_IMAGES}, not ${count}`);
234
+ }
235
+ if (options.size !== undefined && options.size !== this.meta.size) {
236
+ throw new Error(`${this.model} draws ${this.meta.size} images, not ${options.size}`);
237
+ }
238
+ const text = promptText(options.prompt).trim();
239
+ if (!text)
240
+ throw new Error("The prompt is empty");
241
+ const sampler = samplerSettings(modelOptions);
242
+ logger.request(`onnx.generateImages ${this.model}`, {
243
+ provider: "onnx",
244
+ model: this.model,
245
+ numberOfImages: count
246
+ });
247
+ // Loading (or switching) and drawing in one task: nothing else releases these sessions meanwhile.
248
+ const images = await serial(async () => {
249
+ const loaded = await this.load(abortSignal ? { signal: abortSignal } : {});
250
+ const ids = fixedLengthIds(loaded.tokenizer.encode(text).ids, loaded.endToken);
251
+ const sprites = await drawSprites({
252
+ Tensor: loaded.ort.Tensor,
253
+ denoiser: loaded.denoiser,
254
+ textEncoder: loaded.textEncoder
255
+ }, ids, count, sampler, abortSignal);
256
+ return Promise.all(sprites.map(async (tokens) => toBase64(await encodePng(spritePixels(tokens, loaded.palette), GRID, GRID))));
257
+ }, abortSignal);
258
+ return {
259
+ id: this.generateId(),
260
+ model: this.model,
261
+ images: images.map((b64Json) => ({ b64Json }))
262
+ };
263
+ }
264
+ catch (error) {
265
+ logger.errors(`onnx.generateImages ${this.model} failed`, {
266
+ error,
267
+ source: "onnx.generateImages"
268
+ });
269
+ throw error;
270
+ }
271
+ }
272
+ }
273
+ /** Most denoising steps one call takes. */
274
+ export const MAX_STEPS = 1000;
275
+ /** The sampler's settings for a call: the defaults, with `modelOptions`' own after checking them. */
276
+ function samplerSettings(options) {
277
+ const { seed, steps, guidanceScale } = options;
278
+ if (steps !== undefined &&
279
+ (!Number.isInteger(steps) || steps < 1 || steps > MAX_STEPS)) {
280
+ throw new Error(`steps must be a whole number from 1 to ${MAX_STEPS}, not ${steps}`);
281
+ }
282
+ if (guidanceScale !== undefined && !Number.isFinite(guidanceScale)) {
283
+ throw new Error(`guidanceScale must be a finite number, not ${guidanceScale}`);
284
+ }
285
+ if (seed !== undefined && !Number.isFinite(seed))
286
+ throw new Error(`seed must be a finite number, not ${seed}`);
287
+ return {
288
+ ...DEFAULT_SAMPLER,
289
+ ...(steps !== undefined && { steps }),
290
+ ...(guidanceScale !== undefined && { guidanceScale }),
291
+ seed: seed ?? Math.floor(Math.random() * 2 ** 32)
292
+ };
293
+ }
294
+ /** An image adapter for one of the catalog's ONNX models. */
295
+ export function onnxImage(model, config = {}) {
296
+ return new OnnxImageAdapter(model, config);
297
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * TanStack AI image adapter for ONNX models in the browser, on ONNX Runtime
3
+ * Web (WebGPU, else WebAssembly). The model catalog (model-meta.ts) is
4
+ * exported here too.
5
+ */
6
+ export { MAX_IMAGES, OnnxImageAdapter, onnxImage } from "./adapter.js";
7
+ export type { Availability, DownloadProgressCallback, OnnxImageConfig, OnnxImageProviderOptions } from "./adapter.js";
8
+ export { ONNX_IMAGE_MODELS, ONNX_MODEL_META } from "./model-meta.js";
9
+ export type { OnnxImageModel, OnnxImageModelMeta, OnnxImageModelSizeByName, OnnxModelFile } from "./model-meta.js";
10
+ export { DEFAULT_WASM_PATHS, ORT_VERSION } from "./runtime.js";
11
+ export type { OnnxBackend } from "./runtime.js";
12
+ export { MODEL_CACHE } from "./storage.js";
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AACtE,YAAY,EACV,YAAY,EACZ,wBAAwB,EACxB,eAAe,EACf,wBAAwB,EACzB,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AACpE,YAAY,EAAE,cAAc,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAClH,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAC9D,YAAY,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * TanStack AI image adapter for ONNX models in the browser, on ONNX Runtime
3
+ * Web (WebGPU, else WebAssembly). The model catalog (model-meta.ts) is
4
+ * exported here too.
5
+ */
6
+ export { MAX_IMAGES, OnnxImageAdapter, onnxImage } from "./adapter.js";
7
+ export { ONNX_IMAGE_MODELS, ONNX_MODEL_META } from "./model-meta.js";
8
+ export { DEFAULT_WASM_PATHS, ORT_VERSION } from "./runtime.js";
9
+ export { MODEL_CACHE } from "./storage.js";
@@ -0,0 +1,13 @@
1
+ /**
2
+ * One queue for everything that touches the page's ONNX sessions: loading,
3
+ * switching to another model or backend, drawing, unloading. Each task runs
4
+ * after the one before has ended, so no task releases sessions another is
5
+ * still using.
6
+ */
7
+ /**
8
+ * Runs `task` after every task queued before it. A caller whose `signal` is
9
+ * aborted while it waits rejects at once, and its task, when its turn
10
+ * comes, rejects without running.
11
+ */
12
+ export declare function serial<T>(task: () => Promise<T>, signal?: AbortSignal): Promise<T>;
13
+ //# sourceMappingURL=lifecycle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lifecycle.d.ts","sourceRoot":"","sources":["../src/lifecycle.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAUH;;;;GAIG;AACH,wBAAgB,MAAM,CAAC,CAAC,EACtB,IAAI,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACtB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,CAAC,CAAC,CAeZ"}
@@ -0,0 +1,34 @@
1
+ /**
2
+ * One queue for everything that touches the page's ONNX sessions: loading,
3
+ * switching to another model or backend, drawing, unloading. Each task runs
4
+ * after the one before has ended, so no task releases sessions another is
5
+ * still using.
6
+ */
7
+ let tail = Promise.resolve();
8
+ /** The reason an aborted signal gives, as an error. */
9
+ const abortReason = (signal) => signal.reason instanceof Error
10
+ ? signal.reason
11
+ : new DOMException("The operation was aborted.", "AbortError");
12
+ /**
13
+ * Runs `task` after every task queued before it. A caller whose `signal` is
14
+ * aborted while it waits rejects at once, and its task, when its turn
15
+ * comes, rejects without running.
16
+ */
17
+ export function serial(task, signal) {
18
+ const run = tail.then(() => {
19
+ signal?.throwIfAborted();
20
+ return task();
21
+ });
22
+ tail = run.catch(() => undefined);
23
+ if (!signal)
24
+ return run;
25
+ if (signal.aborted)
26
+ return Promise.reject(abortReason(signal));
27
+ return new Promise((resolve, reject) => {
28
+ const onAbort = () => reject(abortReason(signal));
29
+ signal.addEventListener("abort", onAbort, { once: true });
30
+ run
31
+ .then(resolve, reject)
32
+ .finally(() => signal.removeEventListener("abort", onAbort));
33
+ });
34
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The catalog: image models this adapter runs, by their Hugging Face
3
+ * repository. Each one's files are pinned to a commit, so a later change
4
+ * to the repository can't change what an app loads.
5
+ */
6
+ /** A model file: its path in the repository and its size in bytes. */
7
+ export type OnnxModelFile = {
8
+ path: string;
9
+ bytes: number;
10
+ };
11
+ /** What a model is and where its files are. */
12
+ export type OnnxImageModelMeta = {
13
+ /** The model's Hugging Face repository, its name for `onnxImage`. */
14
+ name: string;
15
+ /** The commit its files are read at. */
16
+ revision: string;
17
+ /** The one size it draws, as TanStack AI's `size` (WIDTHxHEIGHT). */
18
+ size: string;
19
+ /** The download, all files together. */
20
+ download: string;
21
+ /** The weights' license. */
22
+ license: string;
23
+ files: {
24
+ /** The denoiser: one pass over the whole canvas per step. */
25
+ denoiser: OnnxModelFile;
26
+ /** The text encoder the denoiser is conditioned on. */
27
+ textEncoder: OnnxModelFile;
28
+ /** The text encoder's tokenizer (Hugging Face `tokenizer.json`). */
29
+ tokenizer: OnnxModelFile;
30
+ /** The colors a pixel token stands for (`palette_rgba`, one RGBA per token). */
31
+ palette: OnnxModelFile;
32
+ };
33
+ };
34
+ /** The catalog's models, by their Hugging Face repository. */
35
+ export declare const ONNX_IMAGE_MODELS: readonly ["cfahlgren1/tessera-small-onnx"];
36
+ /** A model of the catalog. */
37
+ export type OnnxImageModel = (typeof ONNX_IMAGE_MODELS)[number];
38
+ /** Each model's entry, by name. */
39
+ export declare const ONNX_MODEL_META: {
40
+ readonly "cfahlgren1/tessera-small-onnx": {
41
+ readonly name: "cfahlgren1/tessera-small-onnx";
42
+ readonly revision: "bef21be58afea4d16be21f5fbe85eaa0cae69290";
43
+ readonly size: "16x16";
44
+ readonly download: "115 MB";
45
+ readonly license: "CC BY-NC 4.0";
46
+ readonly files: {
47
+ readonly denoiser: {
48
+ readonly path: "tessera_w8.onnx";
49
+ readonly bytes: 50834182;
50
+ };
51
+ readonly textEncoder: {
52
+ readonly path: "clip_text_w8.onnx";
53
+ readonly bytes: 64060515;
54
+ };
55
+ readonly tokenizer: {
56
+ readonly path: "tokenizer.json";
57
+ readonly bytes: 0;
58
+ };
59
+ readonly palette: {
60
+ readonly path: "palette.json";
61
+ readonly bytes: 0;
62
+ };
63
+ };
64
+ };
65
+ };
66
+ /** The size each model draws, for TanStack AI's `size` option. */
67
+ export type OnnxImageModelSizeByName = {
68
+ [K in OnnxImageModel]: (typeof ONNX_MODEL_META)[K]["size"];
69
+ };
70
+ /** A file's URL at the model's pinned commit. */
71
+ export declare const fileUrl: (meta: OnnxImageModelMeta, file: OnnxModelFile) => string;
72
+ //# sourceMappingURL=model-meta.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model-meta.d.ts","sourceRoot":"","sources":["../src/model-meta.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,sEAAsE;AACtE,MAAM,MAAM,aAAa,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAA;AAE3D,+CAA+C;AAC/C,MAAM,MAAM,kBAAkB,GAAG;IAC/B,qEAAqE;IACrE,IAAI,EAAE,MAAM,CAAA;IACZ,wCAAwC;IACxC,QAAQ,EAAE,MAAM,CAAA;IAChB,qEAAqE;IACrE,IAAI,EAAE,MAAM,CAAA;IACZ,wCAAwC;IACxC,QAAQ,EAAE,MAAM,CAAA;IAChB,4BAA4B;IAC5B,OAAO,EAAE,MAAM,CAAA;IACf,KAAK,EAAE;QACL,6DAA6D;QAC7D,QAAQ,EA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