@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.
@@ -68,6 +68,35 @@ export function mountTranscriptView(host, queue, o = {}) {
68
68
  l.add(queue.subscribe(draw));
69
69
  return { dispose: () => l.off() };
70
70
  }
71
+ const AV = /\.(mp4|m4v|mov|webm|mkv|avi|mpe?g|ogv|m4a|mp3|wav|flac|ogg|opus|aac|wma|3gp)$/i;
72
+ /** A file a speech run can read: audio or video by type or by name. */
73
+ export const isMedia = (f) => /^(audio|video)\//.test(f.type) || AV.test(f.name);
74
+ async function walk(e, out, depth = 0) {
75
+ if (e.isFile && e.file)
76
+ out.push(await new Promise((ok, bad) => e.file(ok, bad)));
77
+ else if (e.isDirectory && e.createReader && depth < 8) {
78
+ const r = e.createReader();
79
+ for (;;) {
80
+ const batch = await new Promise((ok, bad) => r.readEntries(ok, bad));
81
+ if (!batch.length)
82
+ break;
83
+ for (const c of batch)
84
+ await walk(c, out, depth + 1);
85
+ }
86
+ }
87
+ }
88
+ /** The files of a drop, with dropped folders read through, media only. */
89
+ export async function droppedFiles(dt) {
90
+ if (!dt)
91
+ return [];
92
+ const entries = [...(dt.items ?? [])].map((i) => i.webkitGetAsEntry?.()).filter((x) => x !== null && x !== undefined);
93
+ if (!entries.length)
94
+ return [...dt.files].filter(isMedia);
95
+ const out = [];
96
+ for (const e of entries)
97
+ await walk(e, out).catch(() => undefined);
98
+ return out.filter(isMedia);
99
+ }
71
100
  /** The drop zone that becomes the transcript. */
72
101
  export function mountTranscribeDrop(host, queue, o = {}) {
73
102
  const l = listeners();
@@ -76,19 +105,23 @@ export function mountTranscribeDrop(host, queue, o = {}) {
76
105
  input.hidden = true;
77
106
  input.multiple = true;
78
107
  input.accept = o.accept ?? "audio/*,video/*";
108
+ const dir = document.createElement("input");
109
+ dir.type = "file";
110
+ dir.hidden = true;
111
+ dir.setAttribute("webkitdirectory", "");
79
112
  const zone = document.createElement("div");
80
113
  const result = document.createElement("div");
81
- host.replaceChildren(zone, result, input);
114
+ host.replaceChildren(zone, result, input, dir);
82
115
  zone.className = "hb-lay-drop";
83
116
  // the result scrolls inside the subject, as the drop first layout's transcript does
84
117
  result.className = "hb-lay-scroll";
85
118
  zone.innerHTML =
86
119
  `<div class="hb-lay-empty"><span class="hb-lay-empty-name">${esc(o.title ?? "drop audio or video")}</span>` +
87
120
  `<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>`;
121
+ `<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.folders ? `<button type="button" class="hb-btn" data-folder>a folder</button>` : ""}${o.sampleLabel ? `<button type="button" class="hb-btn" data-sample>${esc(o.sampleLabel)}</button>` : ""}</div></div>`;
89
122
  const view = mountTranscriptView(result, queue, o);
90
123
  const take = (list) => {
91
- const files = list ? [...list] : [];
124
+ const files = list ? [...list].filter(isMedia) : [];
92
125
  if (files.length)
93
126
  queue.add(files);
94
127
  };
@@ -100,7 +133,11 @@ export function mountTranscribeDrop(host, queue, o = {}) {
100
133
  l.on(host, "drop", (e) => {
101
134
  e.preventDefault();
102
135
  zone.classList.remove("is-hot");
103
- take(e.dataTransfer?.files);
136
+ void droppedFiles(e.dataTransfer).then((fs) => fs.length && queue.add(fs));
137
+ });
138
+ l.on(dir, "change", () => {
139
+ take(dir.files);
140
+ dir.value = "";
104
141
  });
105
142
  l.on(input, "change", () => {
106
143
  take(input.files);
@@ -110,6 +147,8 @@ export function mountTranscribeDrop(host, queue, o = {}) {
110
147
  const t = e.target;
111
148
  if (t.closest("[data-pick]"))
112
149
  input.click();
150
+ else if (t.closest("[data-folder]"))
151
+ dir.click();
113
152
  else if (t.closest("[data-sample]"))
114
153
  o.onSample?.();
115
154
  });
@@ -120,6 +159,7 @@ export function mountTranscribeDrop(host, queue, o = {}) {
120
159
  }));
121
160
  return {
122
161
  pick: () => input.click(),
162
+ pickFolder: () => dir.click(),
123
163
  dispose() {
124
164
  l.off();
125
165
  view.dispose();
@@ -201,3 +241,49 @@ export function mountTranscriptExports(host, queue, o = {}) {
201
241
  l.add(queue.subscribe(draw));
202
242
  return { dispose: () => l.off() };
203
243
  }
244
+ /**
245
+ * ExportMenu: the selected transcript as txt, srt, vtt or json, a copy, and
246
+ * every finished transcript as one zip with a manifest, plus undo and redo of
247
+ * edits. Nothing shows until there is text; undo shows once there is a change.
248
+ * `go` makes the first export the one pink action.
249
+ */
250
+ export function mountExportMenu(host, queue, o = {}) {
251
+ const l = listeners();
252
+ const save = o.save ?? ((name, data, type) => download(name, typeof data === "string" ? data : new Blob([data], { type }), type));
253
+ const draw = (s) => {
254
+ const c = pickedOf(s);
255
+ const done = s.channels.filter((x) => x.segments.length).length;
256
+ host.innerHTML = c?.segments.length
257
+ ? `<div class="hb-toolbar" role="group" aria-label="export">${["txt", "srt", "vtt", "json"].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>${done ? `<button type="button" class="hb-btn" data-zip>all ${done} as zip</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>`
258
+ : "";
259
+ };
260
+ l.on(host, "click", (e) => {
261
+ const t = e.target;
262
+ const ex = t.closest("[data-ex]");
263
+ if (ex) {
264
+ const f = queue.exportAs(ex.dataset.ex);
265
+ if (f)
266
+ save(f.name, f.text, f.type);
267
+ return;
268
+ }
269
+ if (t.closest("[data-zip]")) {
270
+ const z = queue.zip(o.tool ? { tool: o.tool } : {});
271
+ if (z)
272
+ save(z.name, z.data, "application/zip");
273
+ return;
274
+ }
275
+ const cp = t.closest("[data-copy]");
276
+ if (cp) {
277
+ const f = queue.exportAs("txt");
278
+ if (f)
279
+ void navigator.clipboard?.writeText(f.text).then(() => (cp.lastChild.textContent = "copied")).catch(() => (cp.lastChild.textContent = "copy blocked"));
280
+ return;
281
+ }
282
+ if (t.closest("[data-undo]"))
283
+ queue.undo();
284
+ else if (t.closest("[data-redo]"))
285
+ queue.redo();
286
+ });
287
+ l.add(queue.subscribe(draw));
288
+ return { dispose: () => l.off() };
289
+ }
package/dist/pick.d.ts CHANGED
@@ -19,6 +19,28 @@ export interface LoadContext {
19
19
  }
20
20
  /** Fetches a model's weights (and may start its runtime). Throws to fail the row. */
21
21
  export type Loader = (rec: ModelRecord, ctx: LoadContext) => Promise<unknown>;
22
+ /**
23
+ * The ids of records whose files are already in a weight store: the cache
24
+ * badge of a picker. A record counts when every file key it names is kept,
25
+ * or, for one its runtime fetches by model id, when any kept url sits under
26
+ * that id on the hub. Records cached elsewhere (WebLLM's own cache) are not seen.
27
+ */
28
+ export declare function storedIds(store: Pick<WeightStore, "keys">, records: readonly ModelRecord[]): Promise<string[]>;
29
+ /** What a hub repo check found: whether it exists, whether it carries onnx files, and the words a row shows. */
30
+ export interface RepoCheck {
31
+ ok: boolean;
32
+ onnx: number;
33
+ note: string;
34
+ }
35
+ /**
36
+ * Checks a hub repo id before it is used as your own model: it exists, it is
37
+ * public, and it carries onnx files transformers.js can run. One request to
38
+ * the hub's model api; no weights are fetched.
39
+ */
40
+ export declare function verifyRepo(repo: string, o?: {
41
+ fetch?: typeof fetch;
42
+ host?: string;
43
+ }): Promise<RepoCheck>;
22
44
  /**
23
45
  * A loader over a weight store: a record with a url fetches that file, a
24
46
  * record with a repo and files fetches each, resuming and checking the
@@ -90,6 +112,7 @@ export interface ModelPick {
90
112
  records?: readonly ModelRecord[] | undefined;
91
113
  loader?: Loader | undefined;
92
114
  onRemove?: PickOptions["onRemove"];
115
+ stored?: Iterable<string> | undefined;
93
116
  }): void;
94
117
  /** What the loader returned for a model. */
95
118
  result(id: string): unknown;
package/dist/pick.js CHANGED
@@ -9,6 +9,54 @@ import { getRepo, hfResolve } from "@hackbuild/weights";
9
9
  import { bytesText, canLoad, loadAll } from "@virgilvox/hackbuild-ui/vanilla";
10
10
  import { ALL_RECORDS, JOBS, jobRecords } from "./jobs.js";
11
11
  import { rowOf } from "./rows.js";
12
+ /**
13
+ * The ids of records whose files are already in a weight store: the cache
14
+ * badge of a picker. A record counts when every file key it names is kept,
15
+ * or, for one its runtime fetches by model id, when any kept url sits under
16
+ * that id on the hub. Records cached elsewhere (WebLLM's own cache) are not seen.
17
+ */
18
+ export async function storedIds(store, records) {
19
+ const keys = await store.keys().catch(() => []);
20
+ if (!keys.length)
21
+ return [];
22
+ const set = new Set(keys);
23
+ return records
24
+ .filter((r) => {
25
+ const ks = weightKeys(r);
26
+ if (ks.length)
27
+ return ks.every((k) => set.has(k));
28
+ const id = r.source.modelId;
29
+ return !!id && keys.some((k) => k.includes(`/${id}/resolve/`));
30
+ })
31
+ .map((r) => r.id);
32
+ }
33
+ /**
34
+ * Checks a hub repo id before it is used as your own model: it exists, it is
35
+ * public, and it carries onnx files transformers.js can run. One request to
36
+ * the hub's model api; no weights are fetched.
37
+ */
38
+ export async function verifyRepo(repo, o = {}) {
39
+ const id = repo.trim().replace(/^https?:\/\/huggingface\.co\//, "").replace(/\/+$/, "");
40
+ if (!/^[\w.-]+\/[\w.-]+$/.test(id))
41
+ return { ok: false, onnx: 0, note: "write it as owner/name." };
42
+ const f = o.fetch ?? globalThis.fetch.bind(globalThis);
43
+ let res;
44
+ try {
45
+ res = await f(`${o.host ?? "https://huggingface.co"}/api/models/${id}`);
46
+ }
47
+ catch {
48
+ return { ok: false, onnx: 0, note: "the hub did not answer. check the connection." };
49
+ }
50
+ if (res.status === 401 || res.status === 403)
51
+ return { ok: false, onnx: 0, note: `${id} is gated or private. it cannot load here.` };
52
+ if (!res.ok)
53
+ return { ok: false, onnx: 0, note: `${id} was not found on the hub.` };
54
+ const body = (await res.json().catch(() => ({})));
55
+ if (body.gated)
56
+ return { ok: false, onnx: 0, note: `${id} is gated. accept its terms on the hub first.` };
57
+ const onnx = (body.siblings ?? []).filter((x) => x.rfilename.endsWith(".onnx")).length;
58
+ return onnx ? { ok: true, onnx, note: `${id} found, ${onnx} onnx files.` } : { ok: false, onnx: 0, note: `${id} has no onnx files. pick an onnx export.` };
59
+ }
12
60
  /**
13
61
  * A loader over a weight store: a record with a url fetches that file, a
14
62
  * record with a repo and files fetches each, resuming and checking the
@@ -204,6 +252,9 @@ export function useModelPick(job, o = {}) {
204
252
  loader = n.loader;
205
253
  if (n.onRemove)
206
254
  onRemove = n.onRemove;
255
+ for (const id of n.stored ?? [])
256
+ if (!state.has(id) || state.get(id) === "none")
257
+ state.set(id, "stored");
207
258
  emit();
208
259
  },
209
260
  result: (id) => results.get(id),