@hackbuild/ai-views 0.1.1 → 0.1.5

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.
@@ -0,0 +1,341 @@
1
+ /**
2
+ * jobLoader: the real loader of a pick. Pass it to `useModelPick(job, {
3
+ * loader: jobLoader(job) })` and a load fetches the runtime (transformers.js,
4
+ * onnxruntime web, WebLLM, wllama, MediaPipe, a voice) from its pinned CDN
5
+ * only when the person presses load, fetches the weights through
6
+ * @hackbuild/weights where the runtime does not fetch its own, and resolves
7
+ * to the object a page uses for that job. Nothing loads at import.
8
+ *
9
+ * One models hub is shared by every jobLoader made with the same options
10
+ * object (or with none), so a model loaded for one view is reused by the next
11
+ * and webgpu work takes one gpu lock.
12
+ */
13
+ import { importEsm, probe } from "@hackbuild/ai-env";
14
+ import { createHub, createRegistry } from "@hackbuild/models";
15
+ import { hfResolve } from "@hackbuild/weights";
16
+ import { ALL_RECORDS } from "./jobs.js";
17
+ /** Pinned CDN modules jobLoader imports at load time. */
18
+ export const RUNTIME_URLS = {
19
+ webllm: ["https://esm.run/@mlc-ai/web-llm@0.2.84", "https://cdn.jsdelivr.net/npm/@mlc-ai/web-llm@0.2.84/+esm"],
20
+ bellows: ["https://cdn.jsdelivr.net/npm/bellows-voice@0.8.0/engine/+esm"],
21
+ kokoro: ["https://cdn.jsdelivr.net/npm/kokoro-js@1.2.1/+esm"],
22
+ };
23
+ const DEFAULT = {};
24
+ /** Lines a factory throws that already say what to do; they reach the row as they are. */
25
+ const PLAIN = {
26
+ kokoro: "kokoro's phonemizer is gpl. pass allowGplPhonemizer: true to load it, or pick another voice.",
27
+ promptApi: "this browser has no built in model. use chrome with the prompt api on.",
28
+ };
29
+ /** Rejects as soon as the signal aborts, whether or not the work below it stops. */
30
+ function untilAbort(p, signal) {
31
+ if (signal.aborted)
32
+ return Promise.reject(new DOMException("stopped", "AbortError"));
33
+ return new Promise((ok, bad) => {
34
+ const stop = () => bad(new DOMException("stopped", "AbortError"));
35
+ signal.addEventListener("abort", stop, { once: true });
36
+ p.then(ok, bad).finally(() => signal.removeEventListener("abort", stop));
37
+ });
38
+ }
39
+ const runtimes = new WeakMap();
40
+ /** The licence of the record a weight url belongs to, for the store's licence line. */
41
+ function licenceFor(url) {
42
+ for (const r of ALL_RECORDS) {
43
+ const id = r.source.modelId ?? r.source.repo;
44
+ if ((id && url.includes(`/${id}/`)) || (r.source.url && url.startsWith(r.source.url)))
45
+ return r.licence;
46
+ }
47
+ return null;
48
+ }
49
+ async function makeRuntime(o) {
50
+ const [{ loadOrt, loadTransformers, ortProvider, runtimeLoader, tjsProvider }, { openWeightStore, transformersCache }] = await Promise.all([import("@hackbuild/devices"), import("@hackbuild/weights")]);
51
+ const [env, store] = await Promise.all([o.env ?? probe(), o.store ?? openWeightStore()]);
52
+ const hub = createHub({ registry: createRegistry(ALL_RECORDS), env });
53
+ const m = o.modules ?? {};
54
+ const rt = { hub, store, modules: m, tokenizers: new Map() };
55
+ const tjsModule = m.transformers ?? loadTransformers();
56
+ const tjs = tjsProvider({ runtime: tjsModule, cache: transformersCache(store, { licenceFor }) });
57
+ const [vision, chatTjs, embed] = await Promise.all([import("@hackbuild/vision"), import("@hackbuild/chat/transformers"), import("@hackbuild/embed")]);
58
+ tjs.loader("depth", vision.depthLoader);
59
+ tjs.loader("vision.caption", vision.vlmLoader);
60
+ tjs.loader("vision.ask", vision.vlmLoader);
61
+ tjs.loader("segment", vision.samLoader);
62
+ tjs.loader("chat", async (ctx) => {
63
+ const { createEngine } = await import("@hackbuild/chat");
64
+ const generator = await ctx.tjs.pipeline("text-generation", ctx.record.source.modelId ?? ctx.record.id, ctx.options);
65
+ const driver = chatTjs.transformersDriver({ module: ctx.tjs, generator: generator, id: ctx.record.id });
66
+ return createEngine(driver, ctx.record.quirks?.systemRole === false ? { quirks: { systemRole: false } } : {});
67
+ });
68
+ // the embed loaders: transformers.js feature extraction, and the static (potion) files through fetch
69
+ embed.attachEmbed(hub, tjs, o.fetch ? { fetch: o.fetch } : {});
70
+ hub.provide("tjs", tjs.factory);
71
+ hub.provide("ort", ortProvider({ runtime: m.ort ?? loadOrt(), store }).factory);
72
+ hub.provide("mediapipe", vision.mediapipeProvider({ runtime: (m.tasksVision ?? vision.loadTasksVision()), store }));
73
+ hub.provide("webllm", (ctx) => webllmFactory(ctx, m));
74
+ hub.provide("wllama", (ctx) => wllamaFactory(ctx, rt));
75
+ hub.provide("prompt-api", async () => {
76
+ const p = await import("@hackbuild/chat/prompt-api");
77
+ if (!p.getLanguageModel())
78
+ throw new Error(PLAIN.promptApi);
79
+ return p.promptApi();
80
+ });
81
+ const voice = (make) => async (ctx) => {
82
+ const e = make(await import("@hackbuild/speak"));
83
+ await e.load({ ...(ctx.signal ? { signal: ctx.signal } : {}), onStatus: (s) => { if (s.progress !== undefined)
84
+ ctx.report("fetch", s.progress); } });
85
+ return e;
86
+ };
87
+ hub.provide("system", voice((s) => s.webSpeechEngine()));
88
+ hub.provide("pocket-worker", voice((s) => s.pocketEngine({})));
89
+ hub.provide("bellows-voice", voice((s) => s.bellowsEngine({ runtime: (m.bellows ?? runtimeLoader([...RUNTIME_URLS.bellows])), rng: o.rng ?? seeded(1) })));
90
+ hub.provide("kokoro-js", async (ctx) => {
91
+ if (!o.allowGplPhonemizer)
92
+ throw new Error(PLAIN.kokoro);
93
+ return voice((s) => s.kokoroEngine({ runtime: (m.kokoro ?? runtimeLoader([...RUNTIME_URLS.kokoro])), allowGplPhonemizer: true }))(ctx);
94
+ });
95
+ return rt;
96
+ }
97
+ async function webllmFactory(ctx, m) {
98
+ const w = await import("@hackbuild/chat/webllm");
99
+ const mod = (await (m.webllm ?? (() => importEsm(RUNTIME_URLS.webllm)))());
100
+ const id = ctx.record.source.modelId ?? ctx.record.id;
101
+ return w.loadWebLLM({
102
+ module: mod,
103
+ modelId: id,
104
+ contextWindow: ctx.record.ctx ?? 4096,
105
+ nativeTools: /hermes/i.test(id),
106
+ onProgress: (p) => {
107
+ const ph = w.webllmPhase(p);
108
+ if (ph.phase !== "ready")
109
+ ctx.report(ph.phase, ph.fraction, ph.file);
110
+ },
111
+ });
112
+ }
113
+ async function wllamaFactory(ctx, rt) {
114
+ const { repo, file } = ctx.record.source;
115
+ if (!repo || !file)
116
+ throw new Error(`${ctx.record.id} names no gguf repo and file.`);
117
+ const w = await import("@hackbuild/chat/wllama");
118
+ const url = hfResolve(repo, ctx.record.source.revision ?? "main") + file;
119
+ const blob = await rt.store.get({ url, key: `gguf:${repo}/${file}`, licence: ctx.record.licence, ...(ctx.record.source.sha256 ? { sha256: ctx.record.source.sha256 } : {}) }, { ...(ctx.signal ? { signal: ctx.signal } : {}), onProgress: (p) => ctx.report("fetch", p.fraction) });
120
+ ctx.report("compile", null);
121
+ const urls = w.wllamaUrls();
122
+ const module = (await (rt.modules.wllama ?? (() => importEsm(urls.esm)))());
123
+ return w.loadWllama({ module, wasmUrl: urls.wasm, blobs: [blob], id: ctx.record.id, ...(ctx.record.ctx ? { nCtx: ctx.record.ctx } : {}) });
124
+ }
125
+ /** A small seeded random source (mulberry32), so no Math.random runs in library code. */
126
+ function seeded(seed) {
127
+ let a = seed >>> 0;
128
+ return () => {
129
+ a = (a + 0x6d2b79f5) >>> 0;
130
+ let t = a;
131
+ t = Math.imul(t ^ (t >>> 15), t | 1);
132
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
133
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
134
+ };
135
+ }
136
+ /** Pixels ({ width, height, data }) as a canvas, which every runtime reads; anything else passes through. */
137
+ export function asImage(img) {
138
+ const p = img;
139
+ if (!p || typeof p !== "object" || p.getContext || !p.data || !p.width || !p.height || typeof document === "undefined")
140
+ return img;
141
+ const c = document.createElement("canvas");
142
+ c.width = p.width;
143
+ c.height = p.height;
144
+ c.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(p.data), p.width, p.height), 0, 0);
145
+ return c;
146
+ }
147
+ /** A file as 16 kHz samples per channel (at most two), decoded by the browser. */
148
+ async function pcm16k(file) {
149
+ const bytes = await file.arrayBuffer();
150
+ const probeCtx = new OfflineAudioContext(1, 1, 16000);
151
+ const buf = await probeCtx.decodeAudioData(bytes);
152
+ const ch = Math.min(2, buf.numberOfChannels);
153
+ const off = new OfflineAudioContext(ch, Math.max(1, Math.ceil(buf.duration * 16000)), 16000);
154
+ const src = off.createBufferSource();
155
+ src.buffer = buf;
156
+ src.connect(off.destination);
157
+ src.start();
158
+ const out = await off.startRendering();
159
+ return Array.from({ length: ch }, (_, i) => out.getChannelData(i));
160
+ }
161
+ /** A level rail folded to at most `bins` bins: loudest frame and whether the gate kept most of it. */
162
+ function railOf(rail, bins = 400) {
163
+ const n = Math.max(1, Math.min(bins, rail.db.length));
164
+ const db = new Array(n).fill(-90);
165
+ const kept = new Array(n).fill(0);
166
+ const count = new Array(n).fill(0);
167
+ for (let i = 0; i < rail.db.length; i++) {
168
+ const b = Math.min(n - 1, Math.floor((i * n) / rail.db.length));
169
+ db[b] = Math.max(db[b], rail.db[i]);
170
+ kept[b] += rail.open[i];
171
+ count[b]++;
172
+ }
173
+ return { db: db.map((x) => Math.round(x * 10) / 10), kept: kept.map((k, b) => (count[b] && k / count[b] >= 0.5 ? 1 : 0)) };
174
+ }
175
+ async function dspOf(rt) {
176
+ rt.dsp ??= rt.modules.dsp
177
+ ? rt.modules.dsp()
178
+ : Promise.all([import("@hackbuild/audio-dsp"), import("@hackbuild/audio-dsp/inline")]).then(([a, i]) => a.loadDsp({ base64: i.AUDIO_DSP_WASM_BASE64 }));
179
+ return rt.dsp;
180
+ }
181
+ async function clipTokenizer(rt, id) {
182
+ let p = rt.tokenizers.get(id);
183
+ if (!p) {
184
+ p = (async () => {
185
+ const load = rt.modules.transformers ?? (await import("@hackbuild/devices")).loadTransformers();
186
+ const tjs = (await load());
187
+ const tok = await tjs.AutoTokenizer.from_pretrained(id);
188
+ return async (text) => Int32Array.from((await tok(text, { padding: "max_length", max_length: 77, truncation: true })).input_ids.data, (v) => Number(v));
189
+ })();
190
+ p.catch(() => rt.tokenizers.delete(id));
191
+ rt.tokenizers.set(id, p);
192
+ }
193
+ return p;
194
+ }
195
+ /** Points on a 4 by 3 grid, for segment everything with a point prompted model. */
196
+ const GRID = [0.2, 0.4, 0.6, 0.8].flatMap((x) => [0.25, 0.5, 0.75].map((y) => ({ x, y })));
197
+ async function adapt(job, rec, value, rt, ctx) {
198
+ const hub = rt.hub;
199
+ const vision = () => import("@hackbuild/vision");
200
+ switch (job) {
201
+ case "transcribe": {
202
+ const t = await import("@hackbuild/transcribe");
203
+ const run = async (file, c) => {
204
+ const [dsp, chans] = await Promise.all([dspOf(rt), pcm16k(file)]);
205
+ const { channel, ...run } = c.options ?? {};
206
+ const lang = run.language ?? ctx.options.language;
207
+ const out = await t.transcribe(hub, dsp, t.toMono(chans, channel ?? "auto"), {
208
+ ...run,
209
+ model: rec.id,
210
+ signal: c.signal,
211
+ ...(lang ? { language: lang } : {}),
212
+ onProgress: (p) => c.onProgress(p.total ? p.done / p.total : 0),
213
+ });
214
+ return { segments: out.segments, dropped: out.dropped, duration: out.stats.dur, language: out.language, model: rec.label ?? rec.id, stats: out.stats, rail: railOf(out.rail) };
215
+ };
216
+ return run;
217
+ }
218
+ case "detect": {
219
+ const v = await vision();
220
+ const fn = async (image) => (await v.detect(hub, asImage(image), { model: rec.id })).map((d) => ({ label: d.label, score: d.score, x: d.box.x, y: d.box.y, w: d.box.w, h: d.box.h }));
221
+ return fn;
222
+ }
223
+ case "depth": {
224
+ const v = await vision();
225
+ const fn = (image) => v.depth(hub, asImage(image), { model: rec.id });
226
+ return fn;
227
+ }
228
+ case "vision": {
229
+ const v = await vision();
230
+ const fn = (image, question) => (question ? v.ask(hub, asImage(image), question, { model: rec.id }) : v.caption(hub, asImage(image), { model: rec.id }));
231
+ return fn;
232
+ }
233
+ case "masks": {
234
+ const v = await vision();
235
+ let key = 0;
236
+ const keys = new WeakMap();
237
+ const keyOf = (img) => keys.get(img) ?? (keys.set(img, `img-${++key}`), `img-${key}`);
238
+ const first = async (image, x, y) => (await v.segment(hub, asImage(image), { points: [{ x, y, label: 1 }] }, { model: rec.id, key: keyOf(image) }))[0];
239
+ if (rec.provides?.includes("segment.everything")) {
240
+ // FastSAM: one pass finds every object; a press picks the one under it from that pass
241
+ let last = null;
242
+ const all = async (image, o = {}) => {
243
+ const key = JSON.stringify(o);
244
+ if (last?.img !== image || last.key !== key)
245
+ last = { img: image, key, list: await v.segmentEverything(hub, asImage(image), { ...o, model: rec.id }) };
246
+ return last.list;
247
+ };
248
+ const fast = {
249
+ segment: async (image, p) => v.instanceAt(await all(image), p.x, p.y)?.mask.data ?? null,
250
+ everything: async (image, o) => (await all(image, o)).map((i, k) => ({ mask: i.mask.data, label: i.label ?? `object ${k + 1}`, score: i.score, box: i.box })),
251
+ };
252
+ return fast;
253
+ }
254
+ const models = {
255
+ segment: async (image, p) => (await first(image, p.x, p.y))?.data ?? null,
256
+ everything: async (image) => {
257
+ const out = [];
258
+ for (const g of GRID) {
259
+ const m = await first(image, g.x * image.width, g.y * image.height);
260
+ if (!m || out.some((o) => overlap(o.mask, m.data) > 0.6))
261
+ continue;
262
+ out.push({ mask: m.data, label: `object ${out.length + 1}`, score: m.score ?? 0 });
263
+ }
264
+ return out;
265
+ },
266
+ };
267
+ return models;
268
+ }
269
+ case "image": {
270
+ const g = await import("@hackbuild/imagegen");
271
+ const gen = await g.loadImagegen(hub, { id: rec.id }, { ...(ctx.signal ? { signal: ctx.signal } : {}) });
272
+ const tokenize = await clipTokenizer(rt, gen.form.tokenizer);
273
+ const job = Object.assign(gen, { tokenize, make: (o) => gen.generate(tokenize, o) });
274
+ return job;
275
+ }
276
+ default:
277
+ return value;
278
+ }
279
+ }
280
+ /** Shared area over the smaller area of two 0 or 255 masks of one size. */
281
+ function overlap(a, b) {
282
+ let both = 0;
283
+ let na = 0;
284
+ let nb = 0;
285
+ for (let i = 0; i < a.length; i++) {
286
+ const x = a[i] > 127;
287
+ const y = b[i] > 127;
288
+ if (x)
289
+ na++;
290
+ if (y)
291
+ nb++;
292
+ if (x && y)
293
+ both++;
294
+ }
295
+ return both / Math.max(1, Math.min(na, nb));
296
+ }
297
+ /** Records jobLoader cannot run yet, with the words a row shows. */
298
+ const NOT_YET = {
299
+ "fastsam-s": "fastsam needs its own decoder, which this loader does not have yet. pick slimsam.",
300
+ };
301
+ /**
302
+ * A real Loader for a job. The runtime and weights load only when a pick
303
+ * calls it; progress goes to `ctx.onProgress`, `ctx.signal` stops it, and a
304
+ * failure throws in plain words. Resolves to {@link JobValues}[job].
305
+ */
306
+ export function jobLoader(job, o = {}) {
307
+ const key = Object.keys(o).length ? o : DEFAULT;
308
+ return async (rec, ctx) => {
309
+ if (NOT_YET[rec.id])
310
+ throw new Error(NOT_YET[rec.id]);
311
+ let rt = runtimes.get(key);
312
+ if (!rt) {
313
+ rt = makeRuntime(o);
314
+ runtimes.set(key, rt);
315
+ rt.catch(() => runtimes.delete(key));
316
+ }
317
+ const r = await rt;
318
+ if (!r.hub.registry.get(rec.id))
319
+ r.hub.registry.add(rec);
320
+ const off = r.hub.onLoad((e) => {
321
+ if (e.id === rec.id && (e.phase === "fetch" || e.phase === "compile" || e.phase === "warm"))
322
+ ctx.onProgress(e.fraction);
323
+ });
324
+ try {
325
+ // an image model loads through loadImagegen, which takes its own lease
326
+ const run = async () => adapt(job, rec, job === "image" ? null : (await r.hub.use({ id: rec.id }, { signal: ctx.signal })).value, r, ctx);
327
+ return await untilAbort(run(), ctx.signal);
328
+ }
329
+ catch (e) {
330
+ if (ctx.signal.aborted)
331
+ throw e;
332
+ const failures = e?.failures ?? e?.cause?.failures ?? [];
333
+ const said = [String(e?.message ?? e), ...failures.map((f) => f.error)].join(" ");
334
+ const plain = Object.values(PLAIN).find((l) => said.includes(l));
335
+ throw new Error(plain ?? (await import("@hackbuild/devices")).humanError("model", e));
336
+ }
337
+ finally {
338
+ off();
339
+ }
340
+ };
341
+ }
@@ -6,7 +6,11 @@
6
6
  * export the mask, a matte or the cutout. With a segment everything model
7
7
  * (FastSAM) one press finds every object; each lands in the found list and
8
8
  * a press adds it to the mask. Models are functions the page passes, so
9
- * stubs run the studio with no weights.
9
+ * stubs run the studio with no weights. Three views (composite, mask,
10
+ * found objects) paint over the canvas; the pointer previews the click cut
11
+ * or lights the found object under it; two fingers or ctrl and the wheel
12
+ * zoom; a page that loads models on demand hears `onWant` when a tool needs
13
+ * one.
10
14
  */
11
15
  import { type MaskMode, type MaskOutput, type MaskPixels, type MaskTool } from "@virgilvox/hackbuild-ui/vanilla";
12
16
  import { type Mounted } from "./dom.js";
@@ -15,6 +19,22 @@ export interface FoundMask {
15
19
  mask: Uint8Array;
16
20
  label: string;
17
21
  score: number;
22
+ /** The box in image pixels, drawn in the found view when present. */
23
+ box?: {
24
+ x: number;
25
+ y: number;
26
+ w: number;
27
+ h: number;
28
+ };
29
+ }
30
+ /** What the canvas shows: the picture with the mask, the mask alone, or every found object in its colour. */
31
+ export type StudioView = "composite" | "mask" | "instances";
32
+ /** Decode settings for a segment everything model (FastSAM): confidence, overlap, smallest area, sigmoid. */
33
+ export interface MaskEverythingOptions {
34
+ confidence?: number;
35
+ iou?: number;
36
+ minArea?: number;
37
+ sigmoid?: boolean;
18
38
  }
19
39
  /** The segment models a mask studio calls: a click segment for one point and a segment everything. */
20
40
  export interface MaskModels {
@@ -23,8 +43,8 @@ export interface MaskModels {
23
43
  x: number;
24
44
  y: number;
25
45
  }) => Promise<Uint8Array | null>;
26
- /** Segment everything: every object at once. */
27
- everything?: (image: MaskPixels) => Promise<FoundMask[]>;
46
+ /** Segment everything: every object at once, with the decode settings when the model takes them. */
47
+ everything?: (image: MaskPixels, o?: MaskEverythingOptions) => Promise<FoundMask[]>;
28
48
  }
29
49
  /** A mask studio tool: the click segment point or one of the hackbuild-ui mask tools. */
30
50
  export type StudioTool = "point" | MaskTool;
@@ -43,9 +63,15 @@ export interface StudioState {
43
63
  coverage: number;
44
64
  zoom: number;
45
65
  busy: string;
66
+ /** The magic wand takes only touching pixels when true. */
67
+ contiguous: boolean;
68
+ view: StudioView;
69
+ /** The found object under the pointer, or -1. */
70
+ hover: number;
46
71
  found: (FoundMask & {
47
72
  on: boolean;
48
73
  colour: string;
74
+ hidden: boolean;
49
75
  })[];
50
76
  /** Masks put aside with a name and a small preview, newest first. */
51
77
  saved: {
@@ -84,15 +110,34 @@ export interface MaskStudio extends Mounted {
84
110
  /** The current mask as ImageData (alpha by default), null before an image. */
85
111
  mask(kind?: MaskOutput): ImageData | null;
86
112
  zoom(dir: 1 | -1 | 0): void;
87
- everything(): Promise<void>;
113
+ /** Set the zoom directly, 0.25 to 6, as a pinch does. */
114
+ zoomTo(z: number): void;
115
+ setView(v: StudioView): void;
116
+ setContiguous(on: boolean): void;
117
+ /** Replace the mask (0 or 255 per image pixel) as one undo step, as the no model modes do. */
118
+ setMask(mask: ArrayLike<number>): void;
119
+ /** Add objects to the found list (a model the page ran itself, or colour clusters). */
120
+ addFound(list: FoundMask[]): void;
121
+ /** Show or hide one found object in the found view. */
122
+ showFound(index: number, on: boolean): void;
123
+ removeFound(index: number): void;
124
+ /** Put every shown found object into the mask, one undo step. */
125
+ mergeFound(): void;
126
+ clearFound(): void;
127
+ /** The picture's pixels, null before an image. */
128
+ pixels(): MaskPixels | null;
129
+ /** Find every object with the segment everything model; asks for it through `onWant` when missing. */
130
+ everything(o?: MaskEverythingOptions): Promise<void>;
88
131
  /** The click segment model at a point in image pixels, as a press with the point tool. */
89
132
  cutAt(x: number, y: number, mode?: MaskMode): Promise<void>;
90
133
  /** Add or take out one found object. */
91
134
  toggleFound(index: number): void;
92
- /** The mask, matte or cutout as a png Blob. */
93
- exportAs(kind: MaskOutput): Promise<Blob | null>;
135
+ /** The mask, matte, cutout or inverse matte as a png Blob. */
136
+ exportAs(kind: MaskOutput | "inverse"): Promise<Blob | null>;
94
137
  hasEverything: boolean;
95
138
  hasSegment: boolean;
139
+ /** The page loads models on demand (`onWant`), so the model tools show before their models. */
140
+ canWant: boolean;
96
141
  state(): StudioState;
97
142
  subscribe(fn: (s: StudioState) => void): () => void;
98
143
  setModels(m: MaskModels): void;
@@ -111,6 +156,11 @@ export interface MaskStudioOptions {
111
156
  onSample?: () => void;
112
157
  /** Name of exported files, without extension. */
113
158
  name?: string;
159
+ /**
160
+ * A tool needs a model the studio does not have yet: the page loads it and calls setModels.
161
+ * With this set, the point tool shows before its model loads.
162
+ */
163
+ onWant?: (kind: "segment" | "everything") => void;
114
164
  }
115
165
  /**
116
166
  * Mounts a mask studio on a host: drop or open an image, then cut masks with the point, wand, brush