@hackbuild/ai-views 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +93 -2
- package/dist/chat.d.ts +91 -0
- package/dist/chat.js +237 -0
- package/dist/dom.d.ts +38 -0
- package/dist/dom.js +67 -0
- package/dist/elements.d.ts +42 -0
- package/dist/elements.js +378 -0
- package/dist/frame.d.ts +55 -0
- package/dist/frame.js +40 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +10 -0
- package/dist/jobs.d.ts +26 -0
- package/dist/jobs.js +49 -0
- package/dist/memory.d.ts +26 -0
- package/dist/memory.js +36 -0
- package/dist/mount-chat.d.ts +38 -0
- package/dist/mount-chat.js +177 -0
- package/dist/mount-frame.d.ts +45 -0
- package/dist/mount-frame.js +237 -0
- package/dist/mount-mask.d.ts +109 -0
- package/dist/mount-mask.js +446 -0
- package/dist/mount-model.d.ts +27 -0
- package/dist/mount-model.js +122 -0
- package/dist/mount-transcribe.d.ts +42 -0
- package/dist/mount-transcribe.js +203 -0
- package/dist/pick.d.ts +132 -0
- package/dist/pick.js +254 -0
- package/dist/rows.d.ts +36 -0
- package/dist/rows.js +147 -0
- package/dist/single/elements.iife.js +9568 -0
- package/dist/single/elements.js +9542 -0
- package/dist/single/index.iife.js +6814 -0
- package/dist/single/index.js +6778 -0
- package/dist/single/vue.iife.js +11334 -0
- package/dist/single/vue.js +11316 -0
- package/dist/transcribe.d.ts +80 -0
- package/dist/transcribe.js +175 -0
- package/dist/vue.d.ts +259 -0
- package/dist/vue.js +199 -0
- package/how.ts +26 -0
- package/package.json +61 -4
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TranscribeDrop, TranscriptView and their rack parts in the DOM, after the
|
|
3
|
+
* earlier transcription tool: the drop zone is the page until a file is in
|
|
4
|
+
* it, then the transcript is. Lines carry their time, edit in place (one
|
|
5
|
+
* undo step each), and export as txt, srt, vtt and json once there is text.
|
|
6
|
+
*/
|
|
7
|
+
import { clockTime, droppedLine, stripStatus } from "@virgilvox/hackbuild-ui/vanilla";
|
|
8
|
+
import { ICON, download, esc, listeners, show } from "./dom.js";
|
|
9
|
+
export function transcriptHtml(c, o = {}) {
|
|
10
|
+
if (!c)
|
|
11
|
+
return `<p class="hb-lay-empty-note">nothing yet. drop a file.</p>`;
|
|
12
|
+
const st = stripStatus(c.status);
|
|
13
|
+
const head = `<div class="hb-panel-hd-inst" role="status">${esc(c.name)}, ${esc(st.word)}${c.status === "working" ? `, ${c.pct}%` : ""}</div>${c.error ? `<p class="hb-lay-empty-note">${esc(c.error)}</p>` : ""}`;
|
|
14
|
+
if (!c.segments.length)
|
|
15
|
+
return `<section class="hb-panel">${head}</section>`;
|
|
16
|
+
const drops = c.dropped.length ? `<li class="hb-tseg-note">${esc(droppedLine(c.dropped))}</li>` : "";
|
|
17
|
+
const rows = c.segments
|
|
18
|
+
.map((s, i) => {
|
|
19
|
+
const t = clockTime(s.start);
|
|
20
|
+
const time = o.onSeek ? `<button type="button" class="hb-tseg-t" data-seek="${s.start}" aria-label="play from ${t}">${t}</button>` : `<span class="hb-tseg-t">${t}</span>`;
|
|
21
|
+
const who = o.speakers ? `<input class="hb-tseg-who" data-who="${i}" placeholder="speaker" aria-label="speaker at ${t}" value="${esc(s.speaker ?? "")}">` : s.speaker ? `<b>${esc(s.speaker)}: </b>` : "";
|
|
22
|
+
return `<li><div class="hb-tseg"><span class="hb-tseg-body">${time}${who}<span class="hb-tseg-text" contenteditable="true" role="textbox" aria-label="text at ${t}" data-line="${i}">${esc(s.text)}</span>${s.edited ? `<span class="hb-tseg-why">edited</span>` : ""}</span></div></li>`;
|
|
23
|
+
})
|
|
24
|
+
.join("");
|
|
25
|
+
const dropped = o.showDropped ? c.dropped.map((d) => `<li><div class="hb-tseg is-dropped"><span class="hb-tseg-body"><span class="hb-tseg-t">${clockTime(d.start)}</span><span class="hb-tseg-text">${esc(d.text)}</span><span class="hb-tseg-why">[${esc(d.why)}]</span></span></div></li>`).join("") : "";
|
|
26
|
+
return `<section class="hb-panel">${head}<ol class="hb-transcript is-edit" aria-label="transcript">${drops}${rows}${dropped}</ol></section>`;
|
|
27
|
+
}
|
|
28
|
+
const pickedOf = (s) => s.channels.find((c) => c.id === s.selected);
|
|
29
|
+
/** The selected channel's transcript over a host. */
|
|
30
|
+
export function mountTranscriptView(host, queue, o = {}) {
|
|
31
|
+
const l = listeners();
|
|
32
|
+
let drawn = "";
|
|
33
|
+
const draw = (s) => {
|
|
34
|
+
// a line being typed in is not redrawn under the caret
|
|
35
|
+
if (host.contains(document.activeElement) && document.activeElement.isContentEditable)
|
|
36
|
+
return;
|
|
37
|
+
const html = transcriptHtml(pickedOf(s), o);
|
|
38
|
+
if (html !== drawn)
|
|
39
|
+
host.innerHTML = drawn = html;
|
|
40
|
+
};
|
|
41
|
+
const commit = (el) => {
|
|
42
|
+
const s = queue.snapshot();
|
|
43
|
+
const c = pickedOf(s);
|
|
44
|
+
if (!c)
|
|
45
|
+
return;
|
|
46
|
+
if (el.dataset.line !== undefined)
|
|
47
|
+
queue.edit(c.id, Number(el.dataset.line), { text: (el.textContent ?? "").trim() });
|
|
48
|
+
else if (el.dataset.who !== undefined)
|
|
49
|
+
queue.edit(c.id, Number(el.dataset.who), { speaker: el.value.trim() });
|
|
50
|
+
};
|
|
51
|
+
l.on(host, "focusout", (e) => {
|
|
52
|
+
commit(e.target);
|
|
53
|
+
draw(queue.snapshot());
|
|
54
|
+
});
|
|
55
|
+
l.on(host, "keydown", (e) => {
|
|
56
|
+
const ke = e;
|
|
57
|
+
const el = ke.target;
|
|
58
|
+
if (ke.key === "Enter" && el.isContentEditable) {
|
|
59
|
+
ke.preventDefault();
|
|
60
|
+
el.blur();
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
l.on(host, "click", (e) => {
|
|
64
|
+
const seek = e.target.closest("[data-seek]");
|
|
65
|
+
if (seek)
|
|
66
|
+
o.onSeek?.(Number(seek.dataset.seek));
|
|
67
|
+
});
|
|
68
|
+
l.add(queue.subscribe(draw));
|
|
69
|
+
return { dispose: () => l.off() };
|
|
70
|
+
}
|
|
71
|
+
/** The drop zone that becomes the transcript. */
|
|
72
|
+
export function mountTranscribeDrop(host, queue, o = {}) {
|
|
73
|
+
const l = listeners();
|
|
74
|
+
const input = document.createElement("input");
|
|
75
|
+
input.type = "file";
|
|
76
|
+
input.hidden = true;
|
|
77
|
+
input.multiple = true;
|
|
78
|
+
input.accept = o.accept ?? "audio/*,video/*";
|
|
79
|
+
const zone = document.createElement("div");
|
|
80
|
+
const result = document.createElement("div");
|
|
81
|
+
host.replaceChildren(zone, result, input);
|
|
82
|
+
zone.className = "hb-lay-drop";
|
|
83
|
+
// the result scrolls inside the subject, as the drop first layout's transcript does
|
|
84
|
+
result.className = "hb-lay-scroll";
|
|
85
|
+
zone.innerHTML =
|
|
86
|
+
`<div class="hb-lay-empty"><span class="hb-lay-empty-name">${esc(o.title ?? "drop audio or video")}</span>` +
|
|
87
|
+
`<p class="hb-lay-empty-note">${esc(o.note ?? "any length. the words are worked out on this machine and the file never leaves it.")}</p>` +
|
|
88
|
+
`<div class="hb-lay-empty-acts"><button type="button" class="hb-btn hb-btn-go" data-pick>${esc(o.pickLabel ?? "choose a file")}</button>${o.sampleLabel ? `<button type="button" class="hb-btn" data-sample>${esc(o.sampleLabel)}</button>` : ""}</div></div>`;
|
|
89
|
+
const view = mountTranscriptView(result, queue, o);
|
|
90
|
+
const take = (list) => {
|
|
91
|
+
const files = list ? [...list] : [];
|
|
92
|
+
if (files.length)
|
|
93
|
+
queue.add(files);
|
|
94
|
+
};
|
|
95
|
+
l.on(host, "dragover", (e) => {
|
|
96
|
+
e.preventDefault();
|
|
97
|
+
zone.classList.add("is-hot");
|
|
98
|
+
});
|
|
99
|
+
l.on(host, "dragleave", () => zone.classList.remove("is-hot"));
|
|
100
|
+
l.on(host, "drop", (e) => {
|
|
101
|
+
e.preventDefault();
|
|
102
|
+
zone.classList.remove("is-hot");
|
|
103
|
+
take(e.dataTransfer?.files);
|
|
104
|
+
});
|
|
105
|
+
l.on(input, "change", () => {
|
|
106
|
+
take(input.files);
|
|
107
|
+
input.value = "";
|
|
108
|
+
});
|
|
109
|
+
l.on(zone, "click", (e) => {
|
|
110
|
+
const t = e.target;
|
|
111
|
+
if (t.closest("[data-pick]"))
|
|
112
|
+
input.click();
|
|
113
|
+
else if (t.closest("[data-sample]"))
|
|
114
|
+
o.onSample?.();
|
|
115
|
+
});
|
|
116
|
+
l.add(queue.subscribe((s) => {
|
|
117
|
+
const empty = s.channels.length === 0;
|
|
118
|
+
show(zone, empty);
|
|
119
|
+
show(result, !empty);
|
|
120
|
+
}));
|
|
121
|
+
return {
|
|
122
|
+
pick: () => input.click(),
|
|
123
|
+
dispose() {
|
|
124
|
+
l.off();
|
|
125
|
+
view.dispose();
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
/** The queue as hackbuild-ui strips: name, state, figures, progress, remove; run and stop. */
|
|
130
|
+
export function mountTranscribeQueue(host, queue) {
|
|
131
|
+
const l = listeners();
|
|
132
|
+
const draw = (s) => {
|
|
133
|
+
const strips = s.channels
|
|
134
|
+
.map((c, i) => {
|
|
135
|
+
const st = stripStatus(c.status);
|
|
136
|
+
return (`<li class="hb-qstrip is-${st.tone || "idle"}${c.id === s.selected ? " is-sel" : ""}${c.status === "done" ? " is-done" : ""}">` +
|
|
137
|
+
`<button type="button" class="hb-qstrip-main" data-sel="${c.id}" aria-pressed="${c.id === s.selected}"><span class="hb-qstrip-n">${String(i + 1).padStart(2, "0")}</span><span class="hb-qstrip-body"><span class="hb-qstrip-hd"><span class="hb-qstrip-name">${esc(c.name)}</span><span class="hb-qstrip-stat">${esc(st.word)}</span></span>` +
|
|
138
|
+
(c.meta.length || c.error ? `<span class="hb-qstrip-meta">${c.meta.map((m) => `<span>${m.label ? `${esc(m.label)} ` : ""}<b${m.tone ? ` class="is-${m.tone}"` : ""}>${esc(m.value)}</b></span>`).join("")}${c.error ? `<span class="is-lo">${esc(c.error)}</span>` : ""}</span>` : "") +
|
|
139
|
+
(c.status === "working" ? `<span class="hb-qstrip-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${c.pct}" aria-label="${esc(c.name)} progress"><i style="--hb-v:${c.pct / 100}"></i></span>` : "") +
|
|
140
|
+
`</span></button>` +
|
|
141
|
+
(s.running ? "" : `<button type="button" class="hb-qstrip-x" data-rm="${c.id}" aria-label="remove ${esc(c.name)}" title="remove">${ICON.x}</button>`) +
|
|
142
|
+
`</li>`);
|
|
143
|
+
})
|
|
144
|
+
.join("");
|
|
145
|
+
const queued = s.channels.some((c) => c.status === "queued");
|
|
146
|
+
host.innerHTML =
|
|
147
|
+
`<ol class="hb-qstrips" aria-label="files">${strips || `<li class="hb-qstrip-empty">no files yet. drop audio or video.</li>`}</ol>` +
|
|
148
|
+
(s.running || queued || s.channels.length ? `<div class="hb-toolbar">${s.running ? `<button type="button" class="hb-btn" data-stop>stop</button>` : queued ? `<button type="button" class="hb-btn" data-run>transcribe</button>` : ""}${s.channels.length && !s.running ? `<button type="button" class="hb-btn" data-clear>clear</button>` : ""}</div>` : "");
|
|
149
|
+
};
|
|
150
|
+
l.on(host, "click", (e) => {
|
|
151
|
+
const t = e.target;
|
|
152
|
+
const sel = t.closest("[data-sel]");
|
|
153
|
+
if (sel)
|
|
154
|
+
return queue.select(Number(sel.dataset.sel));
|
|
155
|
+
const rm = t.closest("[data-rm]");
|
|
156
|
+
if (rm)
|
|
157
|
+
return queue.remove(Number(rm.dataset.rm));
|
|
158
|
+
if (t.closest("[data-run]"))
|
|
159
|
+
void queue.start();
|
|
160
|
+
else if (t.closest("[data-stop]"))
|
|
161
|
+
queue.stop();
|
|
162
|
+
else if (t.closest("[data-clear]"))
|
|
163
|
+
queue.clear();
|
|
164
|
+
});
|
|
165
|
+
l.add(queue.subscribe(draw));
|
|
166
|
+
return { dispose: () => l.off() };
|
|
167
|
+
}
|
|
168
|
+
/** Exports and undo for the selected transcript. Nothing shows until there is text; undo shows once there is a change. */
|
|
169
|
+
/** `go` makes the first export the one pink action: the next thing to do once there is text. */
|
|
170
|
+
export function mountTranscriptExports(host, queue, o = {}) {
|
|
171
|
+
const l = listeners();
|
|
172
|
+
const kinds = ["txt", "srt", "vtt", "json"];
|
|
173
|
+
const draw = (s) => {
|
|
174
|
+
const c = pickedOf(s);
|
|
175
|
+
const has = !!c?.segments.length;
|
|
176
|
+
host.innerHTML = has
|
|
177
|
+
? `<div class="hb-toolbar" role="group" aria-label="export">${kinds.map((k, i) => `<button type="button" class="hb-btn${o.go && i === 0 ? " hb-btn-go" : ""}" data-ex="${k}">${o.go && i === 0 ? `save ${k}` : k}</button>`).join("")}<button type="button" class="hb-btn" data-copy>${ICON.copy}copy</button>${s.canUndo ? `<button type="button" class="hb-iconbtn" data-undo aria-label="undo the last edit" title="undo">${ICON.undo}</button>` : ""}${s.canRedo ? `<button type="button" class="hb-iconbtn" data-redo aria-label="redo" title="redo">${ICON.redo}</button>` : ""}</div>`
|
|
178
|
+
: "";
|
|
179
|
+
};
|
|
180
|
+
l.on(host, "click", (e) => {
|
|
181
|
+
const t = e.target;
|
|
182
|
+
const ex = t.closest("[data-ex]");
|
|
183
|
+
if (ex) {
|
|
184
|
+
const f = queue.exportAs(ex.dataset.ex);
|
|
185
|
+
if (f)
|
|
186
|
+
(o.save ?? download)(f.name, f.text, f.type);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const cp = t.closest("[data-copy]");
|
|
190
|
+
if (cp) {
|
|
191
|
+
const f = queue.exportAs("txt");
|
|
192
|
+
if (f)
|
|
193
|
+
void navigator.clipboard?.writeText(f.text).then(() => (cp.lastChild.textContent = "copied")).catch(() => (cp.lastChild.textContent = "copy blocked"));
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if (t.closest("[data-undo]"))
|
|
197
|
+
queue.undo();
|
|
198
|
+
else if (t.closest("[data-redo]"))
|
|
199
|
+
queue.redo();
|
|
200
|
+
});
|
|
201
|
+
l.add(queue.subscribe(draw));
|
|
202
|
+
return { dispose: () => l.off() };
|
|
203
|
+
}
|
package/dist/pick.d.ts
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* useModelPick(job): the state behind a model picker. It turns the job's
|
|
3
|
+
* records into rows fitted to this machine, keeps the choice, the options
|
|
4
|
+
* and the load state of each model, and loads through @hackbuild/weights
|
|
5
|
+
* with progress. Framework free: a view subscribes and redraws; the Vue
|
|
6
|
+
* component and the custom element both sit on it.
|
|
7
|
+
*/
|
|
8
|
+
import type { Env } from "@hackbuild/ai-env";
|
|
9
|
+
import type { ModelRecord, StorageEstimate } from "@hackbuild/models";
|
|
10
|
+
import { type WeightStore } from "@hackbuild/weights";
|
|
11
|
+
import { type ModelOption, type ModelRow, type OwnKind } from "@virgilvox/hackbuild-ui/vanilla";
|
|
12
|
+
import { type Job } from "./jobs.js";
|
|
13
|
+
export interface LoadContext {
|
|
14
|
+
signal: AbortSignal;
|
|
15
|
+
/** 0 to 1, or null while the total is unknown. */
|
|
16
|
+
onProgress: (fraction: number | null) => void;
|
|
17
|
+
options: Record<string, string>;
|
|
18
|
+
}
|
|
19
|
+
/** Fetches a model's weights (and may start its runtime). Throws to fail the row. */
|
|
20
|
+
export type Loader = (rec: ModelRecord, ctx: LoadContext) => Promise<unknown>;
|
|
21
|
+
/**
|
|
22
|
+
* A loader over a weight store: a record with a url fetches that file, a
|
|
23
|
+
* record with a repo and files fetches each, resuming and checking the
|
|
24
|
+
* SHA-256 when the record has one. Records a runtime fetches itself (WebLLM,
|
|
25
|
+
* transformers.js model ids) need the app's loader.
|
|
26
|
+
*/
|
|
27
|
+
/** The cache keys of a record's files in a weight store, as weightsLoader writes them. */
|
|
28
|
+
export declare function weightKeys(rec: ModelRecord): string[];
|
|
29
|
+
export declare function weightsLoader(store: WeightStore): Loader;
|
|
30
|
+
/** Deletes a stored model's files from a weight store: the remove of a picker. */
|
|
31
|
+
export declare function weightsRemover(store: WeightStore): (rec: ModelRecord) => Promise<void>;
|
|
32
|
+
export interface PickOptions {
|
|
33
|
+
/** Records to pick from; default every record the views know. */
|
|
34
|
+
records?: readonly ModelRecord[];
|
|
35
|
+
env?: Env;
|
|
36
|
+
estimate?: StorageEstimate | null;
|
|
37
|
+
/** Loads a model; required to load. weightsLoader(store) fetches files; a page with a runtime passes its own. */
|
|
38
|
+
loader?: Loader;
|
|
39
|
+
/** Deletes a stored model's weights; weightsRemover(store) does it through @hackbuild/weights. */
|
|
40
|
+
onRemove?: (rec: ModelRecord) => Promise<void> | void;
|
|
41
|
+
/** Ids already on this machine. */
|
|
42
|
+
stored?: Iterable<string>;
|
|
43
|
+
chosen?: string;
|
|
44
|
+
/** Options a job adds to every row, like a language select for speech. */
|
|
45
|
+
extra?: (rec: ModelRecord) => readonly ModelOption[];
|
|
46
|
+
}
|
|
47
|
+
export interface PickSnapshot {
|
|
48
|
+
job: Job;
|
|
49
|
+
title: string;
|
|
50
|
+
empty: string;
|
|
51
|
+
rows: ModelRow[];
|
|
52
|
+
chosen: string;
|
|
53
|
+
row: ModelRow | undefined;
|
|
54
|
+
/** What the loader returned for the chosen model, once it is loaded (an engine, a session). */
|
|
55
|
+
loaded: unknown;
|
|
56
|
+
}
|
|
57
|
+
export interface ModelPick {
|
|
58
|
+
readonly job: Job;
|
|
59
|
+
snapshot(): PickSnapshot;
|
|
60
|
+
subscribe(fn: (s: PickSnapshot) => void): () => void;
|
|
61
|
+
choose(id: string): void;
|
|
62
|
+
/** Load the chosen model, or `id`, through the loader. Rejects when there is no loader or the load fails; the row shows it. */
|
|
63
|
+
load(id?: string): Promise<void>;
|
|
64
|
+
cancel(id?: string): void;
|
|
65
|
+
/** Delete a stored model through onRemove, then forget it. */
|
|
66
|
+
remove(id: string): Promise<void>;
|
|
67
|
+
option(id: string, key: string, value: string): void;
|
|
68
|
+
/** Options set on a row. */
|
|
69
|
+
optionsOf(id: string): Record<string, string>;
|
|
70
|
+
/** Add a model from a "your own" form; returns its id. */
|
|
71
|
+
custom(kind: OwnKind, values: Record<string, string>): string;
|
|
72
|
+
/** New machine facts (env, storage) or records. */
|
|
73
|
+
update(o: {
|
|
74
|
+
env?: Env | undefined;
|
|
75
|
+
estimate?: StorageEstimate | null | undefined;
|
|
76
|
+
records?: readonly ModelRecord[] | undefined;
|
|
77
|
+
loader?: Loader | undefined;
|
|
78
|
+
onRemove?: PickOptions["onRemove"];
|
|
79
|
+
}): void;
|
|
80
|
+
/** What the loader returned for a model. */
|
|
81
|
+
result(id: string): unknown;
|
|
82
|
+
record(id: string): ModelRecord | undefined;
|
|
83
|
+
/** The error of the last failed load of a row. */
|
|
84
|
+
error(id: string): string | undefined;
|
|
85
|
+
}
|
|
86
|
+
/** A record for a "your own" form. Its licence is unknown until the person reads the card. */
|
|
87
|
+
export declare function ownRecord(job: Job, kind: OwnKind, v: Record<string, string>): ModelRecord;
|
|
88
|
+
/**
|
|
89
|
+
* The row a picker starts on: the first "start here" record that fits this
|
|
90
|
+
* machine, else the first that fits and is fast or steady, else the first
|
|
91
|
+
* that fits, else the first.
|
|
92
|
+
*/
|
|
93
|
+
export declare function defaultPick(records: readonly ModelRecord[], env?: Env, estimate?: StorageEstimate | null): string;
|
|
94
|
+
export declare function useModelPick(job: Job, o?: PickOptions): ModelPick;
|
|
95
|
+
/** A preset for a tool with several jobs: one pick per job. */
|
|
96
|
+
export interface PickPreset {
|
|
97
|
+
id: string;
|
|
98
|
+
label: string;
|
|
99
|
+
picks: Partial<Record<Job, string>>;
|
|
100
|
+
}
|
|
101
|
+
export interface JobLine {
|
|
102
|
+
job: Job;
|
|
103
|
+
label: string;
|
|
104
|
+
required: boolean;
|
|
105
|
+
row: ModelRow | undefined;
|
|
106
|
+
}
|
|
107
|
+
/** Several pickers as one rack: a line per job, presets with their totals, and load all. */
|
|
108
|
+
export interface JobsPick {
|
|
109
|
+
readonly picks: ReadonlyMap<Job, ModelPick>;
|
|
110
|
+
lines(): JobLine[];
|
|
111
|
+
presets(): {
|
|
112
|
+
id: string;
|
|
113
|
+
label: string;
|
|
114
|
+
total: string;
|
|
115
|
+
}[];
|
|
116
|
+
applyPreset(id: string): void;
|
|
117
|
+
/** "load all, 1.2 gb" and the ids it would fetch. */
|
|
118
|
+
all(): {
|
|
119
|
+
ids: string[];
|
|
120
|
+
label: string;
|
|
121
|
+
};
|
|
122
|
+
loadAll(): Promise<void>;
|
|
123
|
+
subscribe(fn: () => void): () => void;
|
|
124
|
+
/** New machine facts, records or loader for every job. */
|
|
125
|
+
update(o: Parameters<ModelPick["update"]>[0]): void;
|
|
126
|
+
setPresets(p: readonly PickPreset[]): void;
|
|
127
|
+
}
|
|
128
|
+
export declare function useJobsPick(jobs: readonly {
|
|
129
|
+
job: Job;
|
|
130
|
+
required?: boolean;
|
|
131
|
+
options?: PickOptions;
|
|
132
|
+
}[], initialPresets?: readonly PickPreset[], shared?: PickOptions): JobsPick;
|
package/dist/pick.js
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* useModelPick(job): the state behind a model picker. It turns the job's
|
|
3
|
+
* records into rows fitted to this machine, keeps the choice, the options
|
|
4
|
+
* and the load state of each model, and loads through @hackbuild/weights
|
|
5
|
+
* with progress. Framework free: a view subscribes and redraws; the Vue
|
|
6
|
+
* component and the custom element both sit on it.
|
|
7
|
+
*/
|
|
8
|
+
import { getRepo, hfResolve } from "@hackbuild/weights";
|
|
9
|
+
import { bytesText, canLoad, loadAll } from "@virgilvox/hackbuild-ui/vanilla";
|
|
10
|
+
import { ALL_RECORDS, JOBS, jobRecords } from "./jobs.js";
|
|
11
|
+
import { rowOf } from "./rows.js";
|
|
12
|
+
/**
|
|
13
|
+
* A loader over a weight store: a record with a url fetches that file, a
|
|
14
|
+
* record with a repo and files fetches each, resuming and checking the
|
|
15
|
+
* SHA-256 when the record has one. Records a runtime fetches itself (WebLLM,
|
|
16
|
+
* transformers.js model ids) need the app's loader.
|
|
17
|
+
*/
|
|
18
|
+
/** The cache keys of a record's files in a weight store, as weightsLoader writes them. */
|
|
19
|
+
export function weightKeys(rec) {
|
|
20
|
+
const s = rec.source;
|
|
21
|
+
if (s.url && !s.repo)
|
|
22
|
+
return [s.url];
|
|
23
|
+
const base = s.repo ? hfResolve(s.repo, s.revision ?? "main") : "";
|
|
24
|
+
const files = s.files?.length ? s.files.map((f) => f.path) : s.file ? [s.file] : [];
|
|
25
|
+
return base ? files.map((f) => base + f) : [];
|
|
26
|
+
}
|
|
27
|
+
export function weightsLoader(store) {
|
|
28
|
+
return async (rec, { signal, onProgress }) => {
|
|
29
|
+
if (rec.noDownload || rec.sizeMB === 0) {
|
|
30
|
+
onProgress(1);
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
const s = rec.source;
|
|
34
|
+
if (s.url && !s.repo) {
|
|
35
|
+
return store.get({ url: s.url, licence: rec.licence, ...(s.sha256 ? { sha256: s.sha256 } : {}) }, { signal, onProgress: (p) => onProgress(p.fraction) });
|
|
36
|
+
}
|
|
37
|
+
const files = s.files?.length ? s.files : s.file ? [{ path: s.file, ...(s.sha256 ? { sha256: s.sha256 } : {}) }] : [];
|
|
38
|
+
if (s.repo && files.length) {
|
|
39
|
+
return getRepo(store, { base: hfResolve(s.repo, s.revision ?? "main"), files, licence: rec.licence }, { signal, onProgress: (p) => onProgress(p.total ? p.loaded / p.total : null) });
|
|
40
|
+
}
|
|
41
|
+
throw new Error(`${rec.label ?? rec.id} loads through its runtime. the page passes a loader for it.`);
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** Deletes a stored model's files from a weight store: the remove of a picker. */
|
|
45
|
+
export function weightsRemover(store) {
|
|
46
|
+
return async (rec) => {
|
|
47
|
+
for (const k of weightKeys(rec))
|
|
48
|
+
await store.evict(k);
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
const OWN_PROVIDES = { chat: ["chat"], transcribe: ["transcribe"], vision: ["vision.ask", "vision.caption"], voice: ["speak"], embed: ["embed"] };
|
|
52
|
+
/** A record for a "your own" form. Its licence is unknown until the person reads the card. */
|
|
53
|
+
export function ownRecord(job, kind, v) {
|
|
54
|
+
const provides = OWN_PROVIDES[job] ?? [job];
|
|
55
|
+
const base = { provides, sizeMB: null, sizeSource: "unknown", licence: "unknown, read the model card", commercial: "unknown", speed: "steady", verdict: "your own" };
|
|
56
|
+
const slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
57
|
+
switch (kind) {
|
|
58
|
+
case "gguf":
|
|
59
|
+
return { ...base, id: `own-${slug(`${v.repo}-${v.file}`)}`, label: v.file || v.repo || "gguf", provider: "wllama", source: { repo: v.repo, file: v.file }, ladder: [{ device: "wasm" }] };
|
|
60
|
+
case "onnx":
|
|
61
|
+
return { ...base, id: `own-${slug(v.repo ?? "onnx")}`, label: (v.repo ?? "").split("/").pop() || "onnx", provider: "tjs", source: { modelId: v.repo }, ladder: [{ device: "webgpu" }, { device: "wasm" }] };
|
|
62
|
+
case "mlc":
|
|
63
|
+
return { ...base, id: `own-${slug(v.url ?? "mlc")}`, label: (v.url ?? "").replace(/\/+$/, "").split("/").pop() || "mlc", provider: "webllm", source: { url: v.url }, ladder: [{ device: "webgpu" }] };
|
|
64
|
+
case "endpoint":
|
|
65
|
+
return { ...base, id: `own-${slug(v.url ?? "endpoint")}`, label: (v.url ?? "").replace(/^https?:\/\//, "").split("/")[0] || "endpoint", provider: "remote", source: { url: v.url }, ladder: [{ device: "remote" }], speed: "fast", verdict: "your endpoint" };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* The row a picker starts on: the first "start here" record that fits this
|
|
70
|
+
* machine, else the first that fits and is fast or steady, else the first
|
|
71
|
+
* that fits, else the first.
|
|
72
|
+
*/
|
|
73
|
+
export function defaultPick(records, env, estimate) {
|
|
74
|
+
const fits = records.filter((r) => rowOf(r, { env, estimate }).unfit === undefined);
|
|
75
|
+
return (fits.find((r) => r.group === "start here") ?? fits.find((r) => r.speed === "fast" || r.speed === "steady") ?? fits[0] ?? records[0])?.id ?? "";
|
|
76
|
+
}
|
|
77
|
+
export function useModelPick(job, o = {}) {
|
|
78
|
+
const def = JOBS[job];
|
|
79
|
+
let records = jobRecords(job, o.records ?? ALL_RECORDS);
|
|
80
|
+
let env = o.env;
|
|
81
|
+
let estimate = o.estimate ?? null;
|
|
82
|
+
let loader = o.loader;
|
|
83
|
+
let onRemove = o.onRemove;
|
|
84
|
+
const results = new Map();
|
|
85
|
+
const own = [];
|
|
86
|
+
const state = new Map();
|
|
87
|
+
const progress = new Map();
|
|
88
|
+
const errors = new Map();
|
|
89
|
+
const options = new Map();
|
|
90
|
+
const aborts = new Map();
|
|
91
|
+
for (const id of o.stored ?? [])
|
|
92
|
+
state.set(id, "stored");
|
|
93
|
+
const all = () => [...records, ...own];
|
|
94
|
+
let chosen = o.chosen ?? defaultPick(all(), env, estimate);
|
|
95
|
+
const subs = new Set();
|
|
96
|
+
const rows = () => all().map((r) => rowOf(r, { env, estimate, state: state.get(r.id), progress: progress.get(r.id), options: options.get(r.id), extra: o.extra?.(r), own: own.includes(r) }));
|
|
97
|
+
const snapshot = () => {
|
|
98
|
+
const rs = rows();
|
|
99
|
+
return { job, title: def.title, empty: def.empty, rows: rs, chosen, row: rs.find((r) => r.id === chosen), loaded: results.get(chosen) };
|
|
100
|
+
};
|
|
101
|
+
const emit = () => {
|
|
102
|
+
const s = snapshot();
|
|
103
|
+
for (const fn of subs)
|
|
104
|
+
fn(s);
|
|
105
|
+
};
|
|
106
|
+
const pick = {
|
|
107
|
+
job,
|
|
108
|
+
snapshot,
|
|
109
|
+
subscribe(fn) {
|
|
110
|
+
subs.add(fn);
|
|
111
|
+
fn(snapshot());
|
|
112
|
+
return () => subs.delete(fn);
|
|
113
|
+
},
|
|
114
|
+
choose(id) {
|
|
115
|
+
if (!all().some((r) => r.id === id) || id === chosen)
|
|
116
|
+
return;
|
|
117
|
+
chosen = id;
|
|
118
|
+
emit();
|
|
119
|
+
},
|
|
120
|
+
async load(id = chosen) {
|
|
121
|
+
const rec = all().find((r) => r.id === id);
|
|
122
|
+
const row = rec && rowOf(rec, { env, estimate, state: state.get(id) });
|
|
123
|
+
if (!rec || !canLoad(row))
|
|
124
|
+
return;
|
|
125
|
+
if (!loader) {
|
|
126
|
+
state.set(id, "error");
|
|
127
|
+
errors.set(id, "no loader. the page passes one to load a model.");
|
|
128
|
+
emit();
|
|
129
|
+
throw new Error(`no loader for ${rec.id}: pass one to useModelPick, such as weightsLoader(store)`);
|
|
130
|
+
}
|
|
131
|
+
const ac = new AbortController();
|
|
132
|
+
aborts.set(id, ac);
|
|
133
|
+
state.set(id, "loading");
|
|
134
|
+
progress.set(id, 0);
|
|
135
|
+
errors.delete(id);
|
|
136
|
+
emit();
|
|
137
|
+
try {
|
|
138
|
+
const out = await loader(rec, {
|
|
139
|
+
signal: ac.signal,
|
|
140
|
+
options: options.get(id) ?? {},
|
|
141
|
+
onProgress: (f) => {
|
|
142
|
+
progress.set(id, f ?? progress.get(id) ?? 0);
|
|
143
|
+
emit();
|
|
144
|
+
},
|
|
145
|
+
});
|
|
146
|
+
results.set(id, out);
|
|
147
|
+
state.set(id, "loaded");
|
|
148
|
+
}
|
|
149
|
+
catch (e) {
|
|
150
|
+
const aborted = ac.signal.aborted;
|
|
151
|
+
state.set(id, aborted ? "none" : "error");
|
|
152
|
+
if (!aborted)
|
|
153
|
+
errors.set(id, e instanceof Error ? e.message : String(e));
|
|
154
|
+
if (!aborted)
|
|
155
|
+
throw e;
|
|
156
|
+
}
|
|
157
|
+
finally {
|
|
158
|
+
aborts.delete(id);
|
|
159
|
+
progress.delete(id);
|
|
160
|
+
emit();
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
cancel(id = chosen) {
|
|
164
|
+
aborts.get(id)?.abort();
|
|
165
|
+
},
|
|
166
|
+
async remove(id) {
|
|
167
|
+
const rec = all().find((r) => r.id === id);
|
|
168
|
+
if (!rec)
|
|
169
|
+
return;
|
|
170
|
+
await onRemove?.(rec);
|
|
171
|
+
state.delete(id);
|
|
172
|
+
results.delete(id);
|
|
173
|
+
emit();
|
|
174
|
+
},
|
|
175
|
+
option(id, key, value) {
|
|
176
|
+
options.set(id, { ...options.get(id), [key]: value });
|
|
177
|
+
emit();
|
|
178
|
+
},
|
|
179
|
+
optionsOf: (id) => ({ ...options.get(id) }),
|
|
180
|
+
custom(kind, values) {
|
|
181
|
+
const rec = ownRecord(job, kind, values);
|
|
182
|
+
const i = own.findIndex((r) => r.id === rec.id);
|
|
183
|
+
if (i >= 0)
|
|
184
|
+
own[i] = rec;
|
|
185
|
+
else
|
|
186
|
+
own.push(rec);
|
|
187
|
+
chosen = rec.id;
|
|
188
|
+
emit();
|
|
189
|
+
return rec.id;
|
|
190
|
+
},
|
|
191
|
+
update(n) {
|
|
192
|
+
if ("env" in n)
|
|
193
|
+
env = n.env;
|
|
194
|
+
if ("estimate" in n)
|
|
195
|
+
estimate = n.estimate ?? null;
|
|
196
|
+
if (n.records)
|
|
197
|
+
records = jobRecords(job, n.records);
|
|
198
|
+
if (n.loader)
|
|
199
|
+
loader = n.loader;
|
|
200
|
+
if (n.onRemove)
|
|
201
|
+
onRemove = n.onRemove;
|
|
202
|
+
emit();
|
|
203
|
+
},
|
|
204
|
+
result: (id) => results.get(id),
|
|
205
|
+
record: (id) => all().find((r) => r.id === id),
|
|
206
|
+
error: (id) => errors.get(id),
|
|
207
|
+
};
|
|
208
|
+
return pick;
|
|
209
|
+
}
|
|
210
|
+
export function useJobsPick(jobs, initialPresets = [], shared = {}) {
|
|
211
|
+
let presets = initialPresets;
|
|
212
|
+
const extra = new Set();
|
|
213
|
+
const picks = new Map(jobs.map((j) => [j.job, useModelPick(j.job, { ...shared, ...j.options })]));
|
|
214
|
+
const required = new Map(jobs.map((j) => [j.job, !!j.required]));
|
|
215
|
+
const chosenRows = () => [...picks.values()].map((p) => p.snapshot().row);
|
|
216
|
+
return {
|
|
217
|
+
picks,
|
|
218
|
+
lines: () => [...picks].map(([job, p]) => ({ job, label: JOBS[job].label, required: required.get(job) ?? false, row: p.snapshot().row })),
|
|
219
|
+
presets: () => presets.map((pr) => {
|
|
220
|
+
let bytes = 0;
|
|
221
|
+
for (const [job, id] of Object.entries(pr.picks)) {
|
|
222
|
+
const row = picks.get(job)?.snapshot().rows.find((r) => r.id === id);
|
|
223
|
+
if (row && row.state !== "stored" && row.state !== "loaded")
|
|
224
|
+
bytes += row.bytes ?? 0;
|
|
225
|
+
}
|
|
226
|
+
return { id: pr.id, label: pr.label, total: bytes > 0 ? `about ${bytesText(bytes)}` : "nothing to fetch" };
|
|
227
|
+
}),
|
|
228
|
+
applyPreset(id) {
|
|
229
|
+
const pr = presets.find((p) => p.id === id);
|
|
230
|
+
if (!pr)
|
|
231
|
+
return;
|
|
232
|
+
for (const [job, mid] of Object.entries(pr.picks))
|
|
233
|
+
picks.get(job)?.choose(mid);
|
|
234
|
+
},
|
|
235
|
+
all: () => loadAll(chosenRows()),
|
|
236
|
+
async loadAll() {
|
|
237
|
+
await Promise.all([...picks.values()].map((p) => p.load().catch(() => undefined)));
|
|
238
|
+
},
|
|
239
|
+
subscribe(fn) {
|
|
240
|
+
const offs = [...picks.values()].map((p) => p.subscribe(() => fn()));
|
|
241
|
+
extra.add(fn);
|
|
242
|
+
return () => (offs.forEach((off) => off()), extra.delete(fn));
|
|
243
|
+
},
|
|
244
|
+
update(o) {
|
|
245
|
+
for (const p of picks.values())
|
|
246
|
+
p.update(o);
|
|
247
|
+
},
|
|
248
|
+
setPresets(p) {
|
|
249
|
+
presets = p;
|
|
250
|
+
for (const fn of extra)
|
|
251
|
+
fn();
|
|
252
|
+
},
|
|
253
|
+
};
|
|
254
|
+
}
|
package/dist/rows.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Catalogue records to hackbuild-ui ModelRow: every word a person reads in
|
|
3
|
+
* the picker is written here, once. The kit draws rows and never reads a
|
|
4
|
+
* record; this module never draws.
|
|
5
|
+
*/
|
|
6
|
+
import type { Env } from "@hackbuild/ai-env";
|
|
7
|
+
import { type ModelRecord, type StorageEstimate } from "@hackbuild/models";
|
|
8
|
+
import { type ModelBackend, type ModelOption, type ModelPickState, type ModelRow, type ModelRowGroup } from "@virgilvox/hackbuild-ui/vanilla";
|
|
9
|
+
export declare function isNoDownload(r: ModelRecord): boolean;
|
|
10
|
+
export declare function isUncensored(r: ModelRecord): boolean;
|
|
11
|
+
/** The group a row sits in. A model on this machine leads; else the record's group, else by size. */
|
|
12
|
+
export declare function groupOf(r: ModelRecord, state?: ModelPickState): ModelRowGroup;
|
|
13
|
+
/** Where it runs here: the first rung this machine can take, else the record's first. */
|
|
14
|
+
export declare function backendOf(r: ModelRecord, env?: Env): ModelBackend;
|
|
15
|
+
/** Download words: "1.7 gb". Null for a record with no download or an unknown size. */
|
|
16
|
+
export declare function sizeWords(r: ModelRecord): string | undefined;
|
|
17
|
+
/** The chevron detail: licence, source, context, quant, runtime, and where the size came from. */
|
|
18
|
+
export declare function detailOf(r: ModelRecord): {
|
|
19
|
+
label: string;
|
|
20
|
+
value: string;
|
|
21
|
+
}[];
|
|
22
|
+
/** The options a chosen row offers: backend when the ladder has gpu and cpu, quant when it has several, context for chat. */
|
|
23
|
+
export declare function optionsOf(r: ModelRecord, values?: Record<string, string>, extra?: readonly ModelOption[]): ModelOption[];
|
|
24
|
+
export interface RowContext {
|
|
25
|
+
env?: Env | undefined;
|
|
26
|
+
estimate?: StorageEstimate | null | undefined;
|
|
27
|
+
state?: ModelPickState | undefined;
|
|
28
|
+
progress?: number | undefined;
|
|
29
|
+
options?: Record<string, string> | undefined;
|
|
30
|
+
/** Options a job adds, like a language for speech. */
|
|
31
|
+
extra?: readonly ModelOption[] | undefined;
|
|
32
|
+
/** A row the person added by hand. */
|
|
33
|
+
own?: boolean | undefined;
|
|
34
|
+
}
|
|
35
|
+
/** One record as one picker row. */
|
|
36
|
+
export declare function rowOf(r: ModelRecord, ctx?: RowContext): ModelRow;
|