@hackbuild/ai-views 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +248 -80
- package/dist/chat.d.ts +18 -2
- package/dist/chat.js +7 -1
- package/dist/elements.d.ts +7 -1
- package/dist/elements.js +1 -1
- package/dist/frame.d.ts +2 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/jobs.d.ts +6 -1
- package/dist/jobs.js +4 -1
- package/dist/loaders.d.ts +100 -0
- package/dist/loaders.js +308 -0
- package/dist/memory.d.ts +9 -0
- package/dist/memory.js +3 -0
- package/dist/mount-chat.d.ts +4 -1
- package/dist/mount-chat.js +2 -1
- package/dist/mount-frame.d.ts +13 -1
- package/dist/mount-frame.js +3 -1
- package/dist/mount-mask.d.ts +19 -1
- package/dist/mount-mask.js +5 -1
- package/dist/mount-model.d.ts +11 -1
- package/dist/mount-model.js +25 -4
- package/dist/mount-transcribe.d.ts +11 -2
- package/dist/mount-transcribe.js +2 -2
- package/dist/pick.d.ts +17 -0
- package/dist/pick.js +6 -0
- package/dist/rows.d.ts +6 -0
- package/dist/rows.js +2 -0
- package/dist/single/elements.iife.js +107 -53
- package/dist/single/elements.js +106 -54
- package/dist/single/index.iife.js +17042 -6168
- package/dist/single/index.js +17040 -6169
- package/dist/single/vue.iife.js +111 -48
- package/dist/single/vue.js +112 -48
- package/dist/transcribe.d.ts +14 -2
- package/dist/transcribe.js +2 -2
- package/dist/vue.d.ts +22 -0
- package/dist/vue.js +22 -0
- package/llms.md +1233 -0
- package/package.json +14 -11
|
@@ -0,0 +1,100 @@
|
|
|
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 { type Env } from "@hackbuild/ai-env";
|
|
14
|
+
import type { ChatEngine } from "@hackbuild/chat";
|
|
15
|
+
import type { Dsp } from "@hackbuild/audio-dsp";
|
|
16
|
+
import type { OrtModule, TjsModule } from "@hackbuild/devices";
|
|
17
|
+
import type { Embedder } from "@hackbuild/embed";
|
|
18
|
+
import type { ClipTokenize, FormOptions, ImageGenerator } from "@hackbuild/imagegen";
|
|
19
|
+
import type { Engine } from "@hackbuild/speak";
|
|
20
|
+
import type { WeightStore } from "@hackbuild/weights";
|
|
21
|
+
import { type Job } from "./jobs.js";
|
|
22
|
+
import type { FrameBox } from "./frame.js";
|
|
23
|
+
import type { MaskModels } from "./mount-mask.js";
|
|
24
|
+
import type { Loader } from "./pick.js";
|
|
25
|
+
import type { Transcriber } from "./transcribe.js";
|
|
26
|
+
/** Pinned CDN modules jobLoader imports at load time. */
|
|
27
|
+
export declare const RUNTIME_URLS: {
|
|
28
|
+
readonly webllm: readonly ["https://esm.run/@mlc-ai/web-llm@0.2.84", "https://cdn.jsdelivr.net/npm/@mlc-ai/web-llm@0.2.84/+esm"];
|
|
29
|
+
readonly bellows: readonly ["https://cdn.jsdelivr.net/npm/bellows-voice@0.8.0/engine/+esm"];
|
|
30
|
+
readonly kokoro: readonly ["https://cdn.jsdelivr.net/npm/kokoro-js@1.2.1/+esm"];
|
|
31
|
+
};
|
|
32
|
+
/** The runtime modules, each a function that imports it. Tests pass fakes; a page leaves them out. */
|
|
33
|
+
export interface RuntimeModules {
|
|
34
|
+
transformers?: () => Promise<TjsModule>;
|
|
35
|
+
ort?: () => Promise<OrtModule>;
|
|
36
|
+
webllm?: () => Promise<unknown>;
|
|
37
|
+
wllama?: () => Promise<unknown>;
|
|
38
|
+
tasksVision?: () => Promise<unknown>;
|
|
39
|
+
kokoro?: () => Promise<unknown>;
|
|
40
|
+
bellows?: () => Promise<unknown>;
|
|
41
|
+
/** The audio dsp core transcription runs on; default the wasm inlined in @hackbuild/audio-dsp. */
|
|
42
|
+
dsp?: () => Promise<Dsp>;
|
|
43
|
+
}
|
|
44
|
+
/** Options for {@link jobLoader}. Share one object between loaders to share one hub. */
|
|
45
|
+
export interface JobLoaderOptions {
|
|
46
|
+
/** Where weights are kept; default `openWeightStore()`. */
|
|
47
|
+
store?: WeightStore | Promise<WeightStore>;
|
|
48
|
+
/** This machine; default `probe()` from @hackbuild/ai-env. */
|
|
49
|
+
env?: Env;
|
|
50
|
+
/** Runtime modules in place of the pinned CDN imports (tests). */
|
|
51
|
+
modules?: RuntimeModules;
|
|
52
|
+
/** Kokoro's phonemizer is GPL-3.0-or-later; it is fetched only when this is true. */
|
|
53
|
+
allowGplPhonemizer?: boolean;
|
|
54
|
+
/** fetch for files a runtime does not fetch itself (static embedders). */
|
|
55
|
+
fetch?: typeof fetch;
|
|
56
|
+
/** Random numbers for the bellows voice; default a fixed seed. */
|
|
57
|
+
rng?: () => number;
|
|
58
|
+
}
|
|
59
|
+
/** A detector as a page calls it: boxes in image pixels, best first. */
|
|
60
|
+
export type DetectFn = (image: unknown) => Promise<FrameBox[]>;
|
|
61
|
+
/** A depth model as a page calls it: 0 to 1 per pixel, larger is nearer (relative inverse depth). */
|
|
62
|
+
export type DepthFn = (image: unknown) => Promise<{
|
|
63
|
+
width: number;
|
|
64
|
+
height: number;
|
|
65
|
+
data: Float32Array;
|
|
66
|
+
}>;
|
|
67
|
+
/** A vision language model as a page calls it: a question about an image (a caption without one), answered in words. */
|
|
68
|
+
export type AskFn = (image: unknown, question?: string) => Promise<string>;
|
|
69
|
+
/** An image model with its CLIP tokenizer: `make` generates with the form's defaults filled in. */
|
|
70
|
+
export type ImageJob = ImageGenerator & {
|
|
71
|
+
tokenize: ClipTokenize;
|
|
72
|
+
make(o: FormOptions): ReturnType<ImageGenerator["generate"]>;
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* What a jobLoader load resolves to, per job: chat a ChatEngine; transcribe a
|
|
76
|
+
* Transcriber; detect a DetectFn; masks MaskModels; depth a DepthFn; vision an
|
|
77
|
+
* AskFn; image an ImageJob; voice a loaded @hackbuild/speak Engine; embed an
|
|
78
|
+
* Embedder. faceswap and landmarks resolve to the hub's loaded value as is.
|
|
79
|
+
*/
|
|
80
|
+
export interface JobValues {
|
|
81
|
+
chat: ChatEngine;
|
|
82
|
+
transcribe: Transcriber;
|
|
83
|
+
detect: DetectFn;
|
|
84
|
+
masks: MaskModels;
|
|
85
|
+
depth: DepthFn;
|
|
86
|
+
vision: AskFn;
|
|
87
|
+
image: ImageJob;
|
|
88
|
+
voice: Engine;
|
|
89
|
+
embed: Embedder;
|
|
90
|
+
faceswap: unknown;
|
|
91
|
+
landmarks: unknown;
|
|
92
|
+
}
|
|
93
|
+
/** Pixels ({ width, height, data }) as a canvas, which every runtime reads; anything else passes through. */
|
|
94
|
+
export declare function asImage(img: unknown): unknown;
|
|
95
|
+
/**
|
|
96
|
+
* A real Loader for a job. The runtime and weights load only when a pick
|
|
97
|
+
* calls it; progress goes to `ctx.onProgress`, `ctx.signal` stops it, and a
|
|
98
|
+
* failure throws in plain words. Resolves to {@link JobValues}[job].
|
|
99
|
+
*/
|
|
100
|
+
export declare function jobLoader<J extends Job>(job: J, o?: JobLoaderOptions): Loader;
|
package/dist/loaders.js
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
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 mono samples, 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 off = new OfflineAudioContext(1, Math.max(1, Math.ceil(buf.duration * 16000)), 16000);
|
|
153
|
+
const src = off.createBufferSource();
|
|
154
|
+
src.buffer = buf;
|
|
155
|
+
src.connect(off.destination);
|
|
156
|
+
src.start();
|
|
157
|
+
return (await off.startRendering()).getChannelData(0);
|
|
158
|
+
}
|
|
159
|
+
async function dspOf(rt) {
|
|
160
|
+
rt.dsp ??= rt.modules.dsp
|
|
161
|
+
? rt.modules.dsp()
|
|
162
|
+
: Promise.all([import("@hackbuild/audio-dsp"), import("@hackbuild/audio-dsp/inline")]).then(([a, i]) => a.loadDsp({ base64: i.AUDIO_DSP_WASM_BASE64 }));
|
|
163
|
+
return rt.dsp;
|
|
164
|
+
}
|
|
165
|
+
async function clipTokenizer(rt, id) {
|
|
166
|
+
let p = rt.tokenizers.get(id);
|
|
167
|
+
if (!p) {
|
|
168
|
+
p = (async () => {
|
|
169
|
+
const load = rt.modules.transformers ?? (await import("@hackbuild/devices")).loadTransformers();
|
|
170
|
+
const tjs = (await load());
|
|
171
|
+
const tok = await tjs.AutoTokenizer.from_pretrained(id);
|
|
172
|
+
return async (text) => Int32Array.from((await tok(text, { padding: "max_length", max_length: 77, truncation: true })).input_ids.data, (v) => Number(v));
|
|
173
|
+
})();
|
|
174
|
+
p.catch(() => rt.tokenizers.delete(id));
|
|
175
|
+
rt.tokenizers.set(id, p);
|
|
176
|
+
}
|
|
177
|
+
return p;
|
|
178
|
+
}
|
|
179
|
+
/** Points on a 4 by 3 grid, for segment everything with a point prompted model. */
|
|
180
|
+
const GRID = [0.2, 0.4, 0.6, 0.8].flatMap((x) => [0.25, 0.5, 0.75].map((y) => ({ x, y })));
|
|
181
|
+
async function adapt(job, rec, value, rt, ctx) {
|
|
182
|
+
const hub = rt.hub;
|
|
183
|
+
const vision = () => import("@hackbuild/vision");
|
|
184
|
+
switch (job) {
|
|
185
|
+
case "transcribe": {
|
|
186
|
+
const t = await import("@hackbuild/transcribe");
|
|
187
|
+
const run = async (file, c) => {
|
|
188
|
+
const [dsp, pcm] = await Promise.all([dspOf(rt), pcm16k(file)]);
|
|
189
|
+
const lang = ctx.options.language;
|
|
190
|
+
const out = await t.transcribe(hub, dsp, pcm, {
|
|
191
|
+
model: rec.id,
|
|
192
|
+
signal: c.signal,
|
|
193
|
+
...(lang ? { language: lang } : {}),
|
|
194
|
+
onProgress: (p) => c.onProgress(p.total ? p.done / p.total : 0),
|
|
195
|
+
});
|
|
196
|
+
return { segments: out.segments, dropped: out.dropped, duration: out.stats.dur, language: out.language, model: rec.label ?? rec.id };
|
|
197
|
+
};
|
|
198
|
+
return run;
|
|
199
|
+
}
|
|
200
|
+
case "detect": {
|
|
201
|
+
const v = await vision();
|
|
202
|
+
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 }));
|
|
203
|
+
return fn;
|
|
204
|
+
}
|
|
205
|
+
case "depth": {
|
|
206
|
+
const v = await vision();
|
|
207
|
+
const fn = (image) => v.depth(hub, asImage(image), { model: rec.id });
|
|
208
|
+
return fn;
|
|
209
|
+
}
|
|
210
|
+
case "vision": {
|
|
211
|
+
const v = await vision();
|
|
212
|
+
const fn = (image, question) => (question ? v.ask(hub, asImage(image), question, { model: rec.id }) : v.caption(hub, asImage(image), { model: rec.id }));
|
|
213
|
+
return fn;
|
|
214
|
+
}
|
|
215
|
+
case "masks": {
|
|
216
|
+
const v = await vision();
|
|
217
|
+
let key = 0;
|
|
218
|
+
const keys = new WeakMap();
|
|
219
|
+
const keyOf = (img) => keys.get(img) ?? (keys.set(img, `img-${++key}`), `img-${key}`);
|
|
220
|
+
const first = async (image, x, y) => (await v.segment(hub, asImage(image), { points: [{ x, y, label: 1 }] }, { model: rec.id, key: keyOf(image) }))[0];
|
|
221
|
+
const models = {
|
|
222
|
+
segment: async (image, p) => (await first(image, p.x, p.y))?.data ?? null,
|
|
223
|
+
everything: async (image) => {
|
|
224
|
+
const out = [];
|
|
225
|
+
for (const g of GRID) {
|
|
226
|
+
const m = await first(image, g.x * image.width, g.y * image.height);
|
|
227
|
+
if (!m || out.some((o) => overlap(o.mask, m.data) > 0.6))
|
|
228
|
+
continue;
|
|
229
|
+
out.push({ mask: m.data, label: `object ${out.length + 1}`, score: m.score ?? 0 });
|
|
230
|
+
}
|
|
231
|
+
return out;
|
|
232
|
+
},
|
|
233
|
+
};
|
|
234
|
+
return models;
|
|
235
|
+
}
|
|
236
|
+
case "image": {
|
|
237
|
+
const g = await import("@hackbuild/imagegen");
|
|
238
|
+
const gen = await g.loadImagegen(hub, { id: rec.id }, { ...(ctx.signal ? { signal: ctx.signal } : {}) });
|
|
239
|
+
const tokenize = await clipTokenizer(rt, gen.form.tokenizer);
|
|
240
|
+
const job = Object.assign(gen, { tokenize, make: (o) => gen.generate(tokenize, o) });
|
|
241
|
+
return job;
|
|
242
|
+
}
|
|
243
|
+
default:
|
|
244
|
+
return value;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/** Shared area over the smaller area of two 0 or 255 masks of one size. */
|
|
248
|
+
function overlap(a, b) {
|
|
249
|
+
let both = 0;
|
|
250
|
+
let na = 0;
|
|
251
|
+
let nb = 0;
|
|
252
|
+
for (let i = 0; i < a.length; i++) {
|
|
253
|
+
const x = a[i] > 127;
|
|
254
|
+
const y = b[i] > 127;
|
|
255
|
+
if (x)
|
|
256
|
+
na++;
|
|
257
|
+
if (y)
|
|
258
|
+
nb++;
|
|
259
|
+
if (x && y)
|
|
260
|
+
both++;
|
|
261
|
+
}
|
|
262
|
+
return both / Math.max(1, Math.min(na, nb));
|
|
263
|
+
}
|
|
264
|
+
/** Records jobLoader cannot run yet, with the words a row shows. */
|
|
265
|
+
const NOT_YET = {
|
|
266
|
+
"fastsam-s": "fastsam needs its own decoder, which this loader does not have yet. pick slimsam.",
|
|
267
|
+
};
|
|
268
|
+
/**
|
|
269
|
+
* A real Loader for a job. The runtime and weights load only when a pick
|
|
270
|
+
* calls it; progress goes to `ctx.onProgress`, `ctx.signal` stops it, and a
|
|
271
|
+
* failure throws in plain words. Resolves to {@link JobValues}[job].
|
|
272
|
+
*/
|
|
273
|
+
export function jobLoader(job, o = {}) {
|
|
274
|
+
const key = Object.keys(o).length ? o : DEFAULT;
|
|
275
|
+
return async (rec, ctx) => {
|
|
276
|
+
if (NOT_YET[rec.id])
|
|
277
|
+
throw new Error(NOT_YET[rec.id]);
|
|
278
|
+
let rt = runtimes.get(key);
|
|
279
|
+
if (!rt) {
|
|
280
|
+
rt = makeRuntime(o);
|
|
281
|
+
runtimes.set(key, rt);
|
|
282
|
+
rt.catch(() => runtimes.delete(key));
|
|
283
|
+
}
|
|
284
|
+
const r = await rt;
|
|
285
|
+
if (!r.hub.registry.get(rec.id))
|
|
286
|
+
r.hub.registry.add(rec);
|
|
287
|
+
const off = r.hub.onLoad((e) => {
|
|
288
|
+
if (e.id === rec.id && (e.phase === "fetch" || e.phase === "compile" || e.phase === "warm"))
|
|
289
|
+
ctx.onProgress(e.fraction);
|
|
290
|
+
});
|
|
291
|
+
try {
|
|
292
|
+
// an image model loads through loadImagegen, which takes its own lease
|
|
293
|
+
const run = async () => adapt(job, rec, job === "image" ? null : (await r.hub.use({ id: rec.id }, { signal: ctx.signal })).value, r, ctx);
|
|
294
|
+
return await untilAbort(run(), ctx.signal);
|
|
295
|
+
}
|
|
296
|
+
catch (e) {
|
|
297
|
+
if (ctx.signal.aborted)
|
|
298
|
+
throw e;
|
|
299
|
+
const failures = e?.failures ?? e?.cause?.failures ?? [];
|
|
300
|
+
const said = [String(e?.message ?? e), ...failures.map((f) => f.error)].join(" ");
|
|
301
|
+
const plain = Object.values(PLAIN).find((l) => said.includes(l));
|
|
302
|
+
throw new Error(plain ?? (await import("@hackbuild/devices")).humanError("model", e));
|
|
303
|
+
}
|
|
304
|
+
finally {
|
|
305
|
+
off();
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
}
|
package/dist/memory.d.ts
CHANGED
|
@@ -5,6 +5,10 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import type { Recall } from "@hackbuild/memory";
|
|
7
7
|
import { type Mounted } from "./dom.js";
|
|
8
|
+
/**
|
|
9
|
+
* One row of a recall trace as text: rank, id, kind, text, BM25, cosine, RRF, score, and whether it
|
|
10
|
+
* went to the model.
|
|
11
|
+
*/
|
|
8
12
|
export interface TraceRow {
|
|
9
13
|
rank: number;
|
|
10
14
|
id: number;
|
|
@@ -17,10 +21,15 @@ export interface TraceRow {
|
|
|
17
21
|
/** Inside the hits handed to the model. */
|
|
18
22
|
used: boolean;
|
|
19
23
|
}
|
|
24
|
+
/** The rows of a recall trace as text, marking the hits handed to the model. */
|
|
20
25
|
export declare function traceRows(r: Pick<Recall, "trace" | "hits">, maxText?: number): TraceRow[];
|
|
26
|
+
/** The parts of a memory recall the inspector shows: trace, hits, query and mode. */
|
|
21
27
|
export type RecallLike = Pick<Recall, "trace" | "hits" | "query" | "mode">;
|
|
28
|
+
/** The HTML of a recall trace table, or an empty note before any recall. */
|
|
22
29
|
export declare function inspectorHtml(rec: RecallLike | null): string;
|
|
30
|
+
/** A mounted memory inspector whose `set` shows a new recall. */
|
|
23
31
|
export interface MemoryInspector extends Mounted {
|
|
24
32
|
set(rec: RecallLike | null): void;
|
|
25
33
|
}
|
|
34
|
+
/** Shows a recall trace as a table on a host. */
|
|
26
35
|
export declare function mountMemoryInspector(host: HTMLElement, rec?: RecallLike | null): MemoryInspector;
|
package/dist/memory.js
CHANGED
|
@@ -7,6 +7,7 @@ import { esc } from "./dom.js";
|
|
|
7
7
|
const n3 = (x) => (Number.isFinite(x) ? x.toFixed(3) : "none");
|
|
8
8
|
// the core ranks from 0 (best) and uses -1 for absent; shown 1 based
|
|
9
9
|
const rank = (r) => (r >= 0 ? `#${r + 1}` : "none");
|
|
10
|
+
/** The rows of a recall trace as text, marking the hits handed to the model. */
|
|
10
11
|
export function traceRows(r, maxText = 80) {
|
|
11
12
|
const used = new Set(r.hits.map((h) => h.item.id));
|
|
12
13
|
return r.trace.map((t, i) => ({
|
|
@@ -21,6 +22,7 @@ export function traceRows(r, maxText = 80) {
|
|
|
21
22
|
used: used.has(t.id),
|
|
22
23
|
}));
|
|
23
24
|
}
|
|
25
|
+
/** The HTML of a recall trace table, or an empty note before any recall. */
|
|
24
26
|
export function inspectorHtml(rec) {
|
|
25
27
|
if (!rec)
|
|
26
28
|
return `<p class="hb-lay-empty-note">no recall yet. ask something to see what memory finds.</p>`;
|
|
@@ -30,6 +32,7 @@ export function inspectorHtml(rec) {
|
|
|
30
32
|
rows.map((x) => `<tr class="${x.used ? "is-mark" : ""}" data-used="${x.used}"><td class="num">${x.rank}</td><td>${esc(x.kind)}</td><td>${esc(x.text)}</td><td>${esc(x.bm25)}</td><td>${esc(x.cos)}</td><td class="num">${x.rrf}</td><td class="num">${x.score}</td></tr>`).join("") +
|
|
31
33
|
`</tbody></table></div>`);
|
|
32
34
|
}
|
|
35
|
+
/** Shows a recall trace as a table on a host. */
|
|
33
36
|
export function mountMemoryInspector(host, rec = null) {
|
|
34
37
|
host.innerHTML = inspectorHtml(rec);
|
|
35
38
|
return { set: (r) => void (host.innerHTML = inspectorHtml(r)), dispose() { } };
|
package/dist/mount-chat.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* ChatPane and Composer in the DOM
|
|
2
|
+
* ChatPane and Composer in the DOM: the
|
|
3
3
|
* thread as hackbuild-ui messages, the reasoning in a fold that is open
|
|
4
4
|
* while it streams, the memory a reply used in a fold under it, copy and
|
|
5
5
|
* redo on the last reply only, and a composer whose send is the one pink
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { type ChatList, type ChatThread, type Turn } from "./chat.js";
|
|
9
9
|
import { type Mounted } from "./dom.js";
|
|
10
|
+
/** Options for `mountChatPane`: the reply's name and the empty state's words. */
|
|
10
11
|
export interface ChatPaneOptions {
|
|
11
12
|
/** The reply's name in its head. */
|
|
12
13
|
name?: string;
|
|
@@ -14,6 +15,7 @@ export interface ChatPaneOptions {
|
|
|
14
15
|
emptyName?: string;
|
|
15
16
|
emptyNote?: string;
|
|
16
17
|
}
|
|
18
|
+
/** The HTML of one chat turn, with its reasoning fold, memory used and stats. */
|
|
17
19
|
export declare function turnHtml(t: Turn, o: {
|
|
18
20
|
name: string;
|
|
19
21
|
last: boolean;
|
|
@@ -21,6 +23,7 @@ export declare function turnHtml(t: Turn, o: {
|
|
|
21
23
|
}): string;
|
|
22
24
|
/** The thread over a host, with the empty state inside it. */
|
|
23
25
|
export declare function mountChatPane(host: HTMLElement, thread: ChatThread, o?: ChatPaneOptions): Mounted;
|
|
26
|
+
/** Options for `mountComposer`: placeholder and accessible label. */
|
|
24
27
|
export interface ComposerOptions {
|
|
25
28
|
placeholder?: string;
|
|
26
29
|
label?: string;
|
package/dist/mount-chat.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* ChatPane and Composer in the DOM
|
|
2
|
+
* ChatPane and Composer in the DOM: the
|
|
3
3
|
* thread as hackbuild-ui messages, the reasoning in a fold that is open
|
|
4
4
|
* while it streams, the memory a reply used in a fold under it, copy and
|
|
5
5
|
* redo on the last reply only, and a composer whose send is the one pink
|
|
@@ -14,6 +14,7 @@ const paras = (t) => t
|
|
|
14
14
|
.filter(Boolean)
|
|
15
15
|
.map((p) => `<div class="hb-msg-text">${esc(p).replace(/\n/g, "<br>")}</div>`)
|
|
16
16
|
.join("");
|
|
17
|
+
/** The HTML of one chat turn, with its reasoning fold, memory used and stats. */
|
|
17
18
|
export function turnHtml(t, o) {
|
|
18
19
|
if (t.role === "user") {
|
|
19
20
|
return `<div class="hb-msg is-user" data-turn="${t.id}"><span class="hb-msg-who"><span class="hb-msg-name">you</span></span><div class="hb-msg-parts">${paras(t.text)}</div></div>`;
|
package/dist/mount-frame.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* FrameView and CameraFeed
|
|
2
|
+
* FrameView and CameraFeed: a
|
|
3
3
|
* frame in a hackbuild-ui camera tile with what the models found drawn
|
|
4
4
|
* over it (boxes with their word and score, landmark points and lines),
|
|
5
5
|
* a count in the corner and the caption under it. CameraFeed opens the
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import { type Mounted } from "./dom.js";
|
|
9
9
|
import { type FrameResults } from "./frame.js";
|
|
10
10
|
type Source = HTMLImageElement | HTMLVideoElement | HTMLCanvasElement;
|
|
11
|
+
/** A mounted frame view: set the source, the results to draw, mirroring, and paint again. */
|
|
11
12
|
export interface FrameView extends Mounted {
|
|
12
13
|
/** An image url, or a live element (a camera video); null shows the empty tile. */
|
|
13
14
|
setSource(src: string | Source | null): Promise<void>;
|
|
@@ -16,13 +17,19 @@ export interface FrameView extends Mounted {
|
|
|
16
17
|
/** Draw again, as after a resize or a new video frame. */
|
|
17
18
|
paint(): void;
|
|
18
19
|
}
|
|
20
|
+
/** Options for `mountFrameView`: empty words, mirroring and the colours of the drawn boxes. */
|
|
19
21
|
export interface FrameViewOptions {
|
|
20
22
|
empty?: string;
|
|
21
23
|
mirror?: boolean;
|
|
22
24
|
/** Ink of the drawn boxes' word strip; default the paper token. */
|
|
23
25
|
palette?: readonly string[];
|
|
24
26
|
}
|
|
27
|
+
/** Draws a frame in a camera tile on a host, with boxes, landmarks, a corner tag and a caption over it. */
|
|
25
28
|
export declare function mountFrameView(host: HTMLElement, o?: FrameViewOptions): FrameView;
|
|
29
|
+
/**
|
|
30
|
+
* A mounted camera feed: start, stop, the video element, whether it is live, and a subscription to
|
|
31
|
+
* live and error changes.
|
|
32
|
+
*/
|
|
26
33
|
export interface CameraFeed extends Mounted {
|
|
27
34
|
start(): Promise<void>;
|
|
28
35
|
stop(): void;
|
|
@@ -33,6 +40,10 @@ export interface CameraFeed extends Mounted {
|
|
|
33
40
|
error: string;
|
|
34
41
|
}) => void): () => void;
|
|
35
42
|
}
|
|
43
|
+
/**
|
|
44
|
+
* Options for `mountCameraFeed`: frames per second, the frame callback, which camera, and whether
|
|
45
|
+
* to draw a tile of its own.
|
|
46
|
+
*/
|
|
36
47
|
export interface CameraFeedOptions {
|
|
37
48
|
/** Called with the video this many times a second while live. Default 4. */
|
|
38
49
|
fps?: number;
|
|
@@ -41,5 +52,6 @@ export interface CameraFeedOptions {
|
|
|
41
52
|
/** Draw the video in a tile of its own; off when a FrameView shows it. */
|
|
42
53
|
tile?: boolean;
|
|
43
54
|
}
|
|
55
|
+
/** Opens the camera into a host and hands the video to `onFrame` at the set rate while it is live. */
|
|
44
56
|
export declare function mountCameraFeed(host: HTMLElement, o?: CameraFeedOptions): CameraFeed;
|
|
45
57
|
export {};
|
package/dist/mount-frame.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* FrameView and CameraFeed
|
|
2
|
+
* FrameView and CameraFeed: a
|
|
3
3
|
* frame in a hackbuild-ui camera tile with what the models found drawn
|
|
4
4
|
* over it (boxes with their word and score, landmark points and lines),
|
|
5
5
|
* a count in the corner and the caption under it. CameraFeed opens the
|
|
@@ -16,6 +16,7 @@ const css = (el, name, fb) => {
|
|
|
16
16
|
return fb;
|
|
17
17
|
}
|
|
18
18
|
};
|
|
19
|
+
/** Draws a frame in a camera tile on a host, with boxes, landmarks, a corner tag and a caption over it. */
|
|
19
20
|
export function mountFrameView(host, o = {}) {
|
|
20
21
|
host.innerHTML = `<div class="hb-frameview"><figure class="hb-camtile" aria-label="frame"><div class="hb-camtile-none" role="status">${esc(o.empty ?? "no frame yet")}</div><canvas aria-hidden="true"></canvas><span class="hb-camtile-tag is-tl" hidden></span></figure><p class="hb-frameview-cap" data-caption aria-live="polite" hidden></p></div>`;
|
|
21
22
|
const fig = host.querySelector("figure");
|
|
@@ -161,6 +162,7 @@ export function mountFrameView(host, o = {}) {
|
|
|
161
162
|
};
|
|
162
163
|
return view;
|
|
163
164
|
}
|
|
165
|
+
/** Opens the camera into a host and hands the video to `onFrame` at the set rate while it is live. */
|
|
164
166
|
export function mountCameraFeed(host, o = {}) {
|
|
165
167
|
const video = document.createElement("video");
|
|
166
168
|
video.autoplay = true;
|
package/dist/mount-mask.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* MaskStudio
|
|
2
|
+
* MaskStudio: drop an image, press a thing
|
|
3
3
|
* to cut it out (a click segment model such as SlimSAM), fix the mask by
|
|
4
4
|
* hand with the wand, brush and lasso of hackbuild-ui maskEditor (x swaps
|
|
5
5
|
* add and erase, [ and ] size the brush, ctrl z undoes), zoom and fit, and
|
|
@@ -16,6 +16,7 @@ export interface FoundMask {
|
|
|
16
16
|
label: string;
|
|
17
17
|
score: number;
|
|
18
18
|
}
|
|
19
|
+
/** The segment models a mask studio calls: a click segment for one point and a segment everything. */
|
|
19
20
|
export interface MaskModels {
|
|
20
21
|
/** Click segment: the mask under one point, in image pixels. */
|
|
21
22
|
segment?: (image: MaskPixels, point: {
|
|
@@ -25,7 +26,12 @@ export interface MaskModels {
|
|
|
25
26
|
/** Segment everything: every object at once. */
|
|
26
27
|
everything?: (image: MaskPixels) => Promise<FoundMask[]>;
|
|
27
28
|
}
|
|
29
|
+
/** A mask studio tool: the click segment point or one of the hackbuild-ui mask tools. */
|
|
28
30
|
export type StudioTool = "point" | MaskTool;
|
|
31
|
+
/**
|
|
32
|
+
* What a mask studio shows: tool, mode, sizes, undo state, coverage, zoom, found and saved masks,
|
|
33
|
+
* image size and the last error.
|
|
34
|
+
*/
|
|
29
35
|
export interface StudioState {
|
|
30
36
|
ready: boolean;
|
|
31
37
|
tool: StudioTool;
|
|
@@ -53,6 +59,10 @@ export interface StudioState {
|
|
|
53
59
|
/** The last failure, in words. */
|
|
54
60
|
error: string;
|
|
55
61
|
}
|
|
62
|
+
/**
|
|
63
|
+
* A mounted mask studio: image, tools, undo, grow and shrink, saved masks, found objects, export,
|
|
64
|
+
* and a subscription to its state.
|
|
65
|
+
*/
|
|
56
66
|
export interface MaskStudio extends Mounted {
|
|
57
67
|
setImage(src: string | HTMLImageElement | HTMLCanvasElement | ImageBitmap | MaskPixels): Promise<void>;
|
|
58
68
|
setTool(t: StudioTool): void;
|
|
@@ -89,6 +99,10 @@ export interface MaskStudio extends Mounted {
|
|
|
89
99
|
/** Open the file picker. */
|
|
90
100
|
pick(): void;
|
|
91
101
|
}
|
|
102
|
+
/**
|
|
103
|
+
* Options for `mountMaskStudio`: the segment models, empty state words, a sample button and the
|
|
104
|
+
* export file name.
|
|
105
|
+
*/
|
|
92
106
|
export interface MaskStudioOptions {
|
|
93
107
|
models?: MaskModels;
|
|
94
108
|
title?: string;
|
|
@@ -98,6 +112,10 @@ export interface MaskStudioOptions {
|
|
|
98
112
|
/** Name of exported files, without extension. */
|
|
99
113
|
name?: string;
|
|
100
114
|
}
|
|
115
|
+
/**
|
|
116
|
+
* Mounts a mask studio on a host: drop or open an image, then cut masks with the point, wand, brush
|
|
117
|
+
* and lasso tools or a segment model.
|
|
118
|
+
*/
|
|
101
119
|
export declare function mountMaskStudio(host: HTMLElement, o?: MaskStudioOptions): MaskStudio;
|
|
102
120
|
/** The tool rail of a studio: point (when a click model is set), wand, brush, lasso, and segment everything (when that model is set). */
|
|
103
121
|
export declare function mountMaskTools(host: HTMLElement, studio: MaskStudio): Mounted;
|
package/dist/mount-mask.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* MaskStudio
|
|
2
|
+
* MaskStudio: drop an image, press a thing
|
|
3
3
|
* to cut it out (a click segment model such as SlimSAM), fix the mask by
|
|
4
4
|
* hand with the wand, brush and lasso of hackbuild-ui maskEditor (x swaps
|
|
5
5
|
* add and erase, [ and ] size the brush, ctrl z undoes), zoom and fit, and
|
|
@@ -33,6 +33,10 @@ function thumbOf(img) {
|
|
|
33
33
|
t.getContext("2d")?.drawImage(c, 0, 0, t.width, t.height);
|
|
34
34
|
return t.toDataURL("image/png");
|
|
35
35
|
}
|
|
36
|
+
/**
|
|
37
|
+
* Mounts a mask studio on a host: drop or open an image, then cut masks with the point, wand, brush
|
|
38
|
+
* and lasso tools or a segment model.
|
|
39
|
+
*/
|
|
36
40
|
export function mountMaskStudio(host, o = {}) {
|
|
37
41
|
let models = o.models ?? {};
|
|
38
42
|
const l = listeners();
|