@hackbuild/ai-views 0.0.0-stage → 0.1.1
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 +241 -2
- package/dist/chat.d.ts +107 -0
- package/dist/chat.js +243 -0
- package/dist/dom.d.ts +38 -0
- package/dist/dom.js +67 -0
- package/dist/elements.d.ts +48 -0
- package/dist/elements.js +378 -0
- package/dist/frame.d.ts +57 -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 +31 -0
- package/dist/jobs.js +52 -0
- package/dist/memory.d.ts +35 -0
- package/dist/memory.js +39 -0
- package/dist/mount-chat.d.ts +41 -0
- package/dist/mount-chat.js +178 -0
- package/dist/mount-frame.d.ts +57 -0
- package/dist/mount-frame.js +239 -0
- package/dist/mount-mask.d.ts +127 -0
- package/dist/mount-mask.js +450 -0
- package/dist/mount-model.d.ts +28 -0
- package/dist/mount-model.js +122 -0
- package/dist/mount-transcribe.d.ts +51 -0
- package/dist/mount-transcribe.js +203 -0
- package/dist/pick.d.ts +149 -0
- package/dist/pick.js +260 -0
- package/dist/rows.d.ts +42 -0
- package/dist/rows.js +149 -0
- package/dist/single/elements.iife.js +9599 -0
- package/dist/single/elements.js +9573 -0
- package/dist/single/index.iife.js +6843 -0
- package/dist/single/index.js +6807 -0
- package/dist/single/vue.iife.js +11376 -0
- package/dist/single/vue.js +11359 -0
- package/dist/transcribe.d.ts +92 -0
- package/dist/transcribe.js +175 -0
- package/dist/vue.d.ts +281 -0
- package/dist/vue.js +221 -0
- package/how.ts +26 -0
- package/llms.md +1133 -0
- package/package.json +62 -4
package/dist/jobs.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Jobs: what a person wants a model for, and the records that can do it.
|
|
3
|
+
* A tool asks for a job ("chat", "transcribe"), never for a provider. The
|
|
4
|
+
* records come from the packages that run them; a record listed in more
|
|
5
|
+
* than one place counts once, the running package's copy first.
|
|
6
|
+
*/
|
|
7
|
+
import { CATALOG } from "@hackbuild/models";
|
|
8
|
+
import { EMBED_RECORDS } from "@hackbuild/embed";
|
|
9
|
+
import { IMAGEGEN_PICKER_RECORDS, IMAGEGEN_RECORDS } from "@hackbuild/imagegen";
|
|
10
|
+
import { SPEAK_RECORDS } from "@hackbuild/speak";
|
|
11
|
+
import { TRANSCRIBE_RECORDS } from "@hackbuild/transcribe";
|
|
12
|
+
import { PICKER_RECORDS, VISION_RECORDS, faceApiRecord } from "@hackbuild/vision";
|
|
13
|
+
/** Base URL of the face-api weights (MIT) on the package CDN. */
|
|
14
|
+
export const FACE_API_BASE = "https://cdn.jsdelivr.net/npm/@vladmandic/face-api@1.7.12/model/";
|
|
15
|
+
const has = (...want) => (caps) => caps.some((c) => want.includes(c));
|
|
16
|
+
/** The words and capability test of every job. */
|
|
17
|
+
export const JOBS = {
|
|
18
|
+
chat: { label: "brain", title: "pick a chat model", empty: "no model", provides: has("chat") },
|
|
19
|
+
transcribe: { label: "ears", title: "pick a speech model", empty: "no speech model", provides: has("transcribe") },
|
|
20
|
+
vision: { label: "eyes", title: "pick a vision model", empty: "no vision model", provides: has("vision.ask", "vision.caption") },
|
|
21
|
+
detect: { label: "detector", title: "pick a detector", empty: "no detector", provides: has("detect") },
|
|
22
|
+
masks: { label: "masks", title: "pick a mask model", empty: "no mask model", provides: has("segment", "segment.everything") },
|
|
23
|
+
image: { label: "image", title: "pick an image model", empty: "no image model", provides: has("imagegen") },
|
|
24
|
+
voice: { label: "voice", title: "pick a voice", empty: "no voice", provides: has("speak") },
|
|
25
|
+
depth: { label: "depth", title: "pick a depth model", empty: "no depth model", provides: has("depth") },
|
|
26
|
+
embed: { label: "memory", title: "pick an embedder", empty: "no embedder", provides: has("embed") },
|
|
27
|
+
faceswap: { label: "face swap", title: "pick the face swap models", empty: "no face model", provides: has("face.detect", "face.embed", "face.swap") },
|
|
28
|
+
landmarks: { label: "landmarks", title: "pick a landmark model", empty: "no landmarks", provides: has("landmarks.face", "landmarks.hand", "landmarks.pose", "landmarks.gesture") },
|
|
29
|
+
};
|
|
30
|
+
/** Every job name, in the order of `JOBS`. */
|
|
31
|
+
export const JOB_NAMES = Object.keys(JOBS);
|
|
32
|
+
/** Every record the views know, the running package's copy of a duplicate first. */
|
|
33
|
+
export const ALL_RECORDS = (() => {
|
|
34
|
+
const seen = new Set();
|
|
35
|
+
const out = [];
|
|
36
|
+
for (const r of [...TRANSCRIBE_RECORDS, ...VISION_RECORDS, ...PICKER_RECORDS, ...SPEAK_RECORDS, ...IMAGEGEN_RECORDS, ...IMAGEGEN_PICKER_RECORDS, ...EMBED_RECORDS, faceApiRecord(FACE_API_BASE), ...CATALOG]) {
|
|
37
|
+
if (seen.has(r.id))
|
|
38
|
+
continue;
|
|
39
|
+
seen.add(r.id);
|
|
40
|
+
out.push(r);
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
})();
|
|
44
|
+
/** The records that do a job, catalogue order kept. */
|
|
45
|
+
export function jobRecords(job, records = ALL_RECORDS) {
|
|
46
|
+
const def = JOBS[job];
|
|
47
|
+
return records.filter((r) => def.provides(r.provides));
|
|
48
|
+
}
|
|
49
|
+
/** Whether a string is a job name. */
|
|
50
|
+
export function isJob(s) {
|
|
51
|
+
return !!s && s in JOBS;
|
|
52
|
+
}
|
package/dist/memory.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The memory inspector folded in from ai-elements: what a recall found, one
|
|
3
|
+
* row per fused candidate, best first, with the ones handed to the model
|
|
4
|
+
* marked. Rows are built here; the markup is hackbuild-ui's table.
|
|
5
|
+
*/
|
|
6
|
+
import type { Recall } from "@hackbuild/memory";
|
|
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
|
+
*/
|
|
12
|
+
export interface TraceRow {
|
|
13
|
+
rank: number;
|
|
14
|
+
id: number;
|
|
15
|
+
kind: string;
|
|
16
|
+
text: string;
|
|
17
|
+
bm25: string;
|
|
18
|
+
cos: string;
|
|
19
|
+
rrf: string;
|
|
20
|
+
score: string;
|
|
21
|
+
/** Inside the hits handed to the model. */
|
|
22
|
+
used: boolean;
|
|
23
|
+
}
|
|
24
|
+
/** The rows of a recall trace as text, marking the hits handed to the model. */
|
|
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. */
|
|
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. */
|
|
29
|
+
export declare function inspectorHtml(rec: RecallLike | null): string;
|
|
30
|
+
/** A mounted memory inspector whose `set` shows a new recall. */
|
|
31
|
+
export interface MemoryInspector extends Mounted {
|
|
32
|
+
set(rec: RecallLike | null): void;
|
|
33
|
+
}
|
|
34
|
+
/** Shows a recall trace as a table on a host. */
|
|
35
|
+
export declare function mountMemoryInspector(host: HTMLElement, rec?: RecallLike | null): MemoryInspector;
|
package/dist/memory.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The memory inspector folded in from ai-elements: what a recall found, one
|
|
3
|
+
* row per fused candidate, best first, with the ones handed to the model
|
|
4
|
+
* marked. Rows are built here; the markup is hackbuild-ui's table.
|
|
5
|
+
*/
|
|
6
|
+
import { esc } from "./dom.js";
|
|
7
|
+
const n3 = (x) => (Number.isFinite(x) ? x.toFixed(3) : "none");
|
|
8
|
+
// the core ranks from 0 (best) and uses -1 for absent; shown 1 based
|
|
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. */
|
|
11
|
+
export function traceRows(r, maxText = 80) {
|
|
12
|
+
const used = new Set(r.hits.map((h) => h.item.id));
|
|
13
|
+
return r.trace.map((t, i) => ({
|
|
14
|
+
rank: i + 1,
|
|
15
|
+
id: t.id,
|
|
16
|
+
kind: t.kind,
|
|
17
|
+
text: t.text.length > maxText ? `${t.text.slice(0, maxText - 3)}...` : t.text,
|
|
18
|
+
bm25: `${rank(t.bm25Rank)} ${n3(t.bm25)}`,
|
|
19
|
+
cos: `${rank(t.vecRank)} ${n3(t.cos)}`,
|
|
20
|
+
rrf: n3(t.rrf),
|
|
21
|
+
score: n3(t.score),
|
|
22
|
+
used: used.has(t.id),
|
|
23
|
+
}));
|
|
24
|
+
}
|
|
25
|
+
/** The HTML of a recall trace table, or an empty note before any recall. */
|
|
26
|
+
export function inspectorHtml(rec) {
|
|
27
|
+
if (!rec)
|
|
28
|
+
return `<p class="hb-lay-empty-note">no recall yet. ask something to see what memory finds.</p>`;
|
|
29
|
+
const rows = traceRows(rec);
|
|
30
|
+
return (`<p class="hb-lay-empty-note" role="status">"${esc(rec.query)}", ${esc(rec.mode)} recall, ${rows.length} found, ${rows.filter((x) => x.used).length} used.</p>` +
|
|
31
|
+
`<div class="hb-scroll-x" data-ux="detail"><table class="hb-table"><thead><tr><th class="num">#</th><th>kind</th><th>text</th><th>bm25</th><th>cosine</th><th class="num">rrf</th><th class="num">score</th></tr></thead><tbody>` +
|
|
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("") +
|
|
33
|
+
`</tbody></table></div>`);
|
|
34
|
+
}
|
|
35
|
+
/** Shows a recall trace as a table on a host. */
|
|
36
|
+
export function mountMemoryInspector(host, rec = null) {
|
|
37
|
+
host.innerHTML = inspectorHtml(rec);
|
|
38
|
+
return { set: (r) => void (host.innerHTML = inspectorHtml(r)), dispose() { } };
|
|
39
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ChatPane and Composer in the DOM: the
|
|
3
|
+
* thread as hackbuild-ui messages, the reasoning in a fold that is open
|
|
4
|
+
* while it streams, the memory a reply used in a fold under it, copy and
|
|
5
|
+
* redo on the last reply only, and a composer whose send is the one pink
|
|
6
|
+
* action and turns into stop while a reply streams.
|
|
7
|
+
*/
|
|
8
|
+
import { type ChatList, type ChatThread, type Turn } from "./chat.js";
|
|
9
|
+
import { type Mounted } from "./dom.js";
|
|
10
|
+
/** Options for `mountChatPane`: the reply's name and the empty state's words. */
|
|
11
|
+
export interface ChatPaneOptions {
|
|
12
|
+
/** The reply's name in its head. */
|
|
13
|
+
name?: string;
|
|
14
|
+
/** The empty state, in Permanent Marker. */
|
|
15
|
+
emptyName?: string;
|
|
16
|
+
emptyNote?: string;
|
|
17
|
+
}
|
|
18
|
+
/** The HTML of one chat turn, with its reasoning fold, memory used and stats. */
|
|
19
|
+
export declare function turnHtml(t: Turn, o: {
|
|
20
|
+
name: string;
|
|
21
|
+
last: boolean;
|
|
22
|
+
busy: boolean;
|
|
23
|
+
}): string;
|
|
24
|
+
/** The thread over a host, with the empty state inside it. */
|
|
25
|
+
export declare function mountChatPane(host: HTMLElement, thread: ChatThread, o?: ChatPaneOptions): Mounted;
|
|
26
|
+
/** Options for `mountComposer`: placeholder and accessible label. */
|
|
27
|
+
export interface ComposerOptions {
|
|
28
|
+
placeholder?: string;
|
|
29
|
+
label?: string;
|
|
30
|
+
}
|
|
31
|
+
/** The composer: Enter sends (Shift Enter adds a line, Escape stops), send is the one pink, stop replaces it while a reply streams. */
|
|
32
|
+
export declare function mountComposer(host: HTMLElement, thread: ChatThread, o?: ComposerOptions): Mounted;
|
|
33
|
+
/** The chat list rail (hackbuild-ui HbConversationList markup): new, open, rename, delete with a second press. */
|
|
34
|
+
export declare function mountChatList(host: HTMLElement, list: ChatList, o?: {
|
|
35
|
+
label?: string;
|
|
36
|
+
}): Mounted;
|
|
37
|
+
/** The context meter (hackbuild-ui `.hb-ctxmeter`): what the next request carries against the model's context. */
|
|
38
|
+
export declare function mountContextMeter(host: HTMLElement, thread: ChatThread, o?: {
|
|
39
|
+
budget?: number | (() => number);
|
|
40
|
+
system?: string | (() => string);
|
|
41
|
+
}): Mounted;
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ChatPane and Composer in the DOM: the
|
|
3
|
+
* thread as hackbuild-ui messages, the reasoning in a fold that is open
|
|
4
|
+
* while it streams, the memory a reply used in a fold under it, copy and
|
|
5
|
+
* redo on the last reply only, and a composer whose send is the one pink
|
|
6
|
+
* action and turns into stop while a reply streams.
|
|
7
|
+
*/
|
|
8
|
+
import { composerKey, coarsePointer, autosize, pinned, contextUse, listMeta } from "@virgilvox/hackbuild-ui/vanilla";
|
|
9
|
+
import { contextSegments } from "./chat.js";
|
|
10
|
+
import { ICON, esc, listeners, scroller } from "./dom.js";
|
|
11
|
+
const paras = (t) => t
|
|
12
|
+
.split(/\n{2,}/)
|
|
13
|
+
.map((p) => p.trim())
|
|
14
|
+
.filter(Boolean)
|
|
15
|
+
.map((p) => `<div class="hb-msg-text">${esc(p).replace(/\n/g, "<br>")}</div>`)
|
|
16
|
+
.join("");
|
|
17
|
+
/** The HTML of one chat turn, with its reasoning fold, memory used and stats. */
|
|
18
|
+
export function turnHtml(t, o) {
|
|
19
|
+
if (t.role === "user") {
|
|
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>`;
|
|
21
|
+
}
|
|
22
|
+
const live = !t.done;
|
|
23
|
+
const think = t.think
|
|
24
|
+
? `<details class="hb-think is-think"${live && !t.text ? " open" : ""}><summary>${live && !t.text ? "thinking" : `reasoning (${t.think.length} chars)`}</summary><pre aria-live="off">${esc(t.think)}</pre></details>`
|
|
25
|
+
: "";
|
|
26
|
+
const body = t.text ? paras(t.text) : live && !t.think ? `<div class="hb-msg-pending">thinking</div>` : "";
|
|
27
|
+
const mem = t.mem?.length
|
|
28
|
+
? `<details class="hb-msg-used"><summary>memory used (${t.mem.length})</summary><ul>${t.mem.map((m) => `<li><span class="hb-msg-used-item">${esc(m.label)}</span>${m.score !== undefined ? `<span class="hb-msg-used-score">${m.score.toFixed(2)}</span>` : ""}</li>`).join("")}</ul></details>`
|
|
29
|
+
: "";
|
|
30
|
+
const acts = t.done && t.text && o.last && !o.busy
|
|
31
|
+
? `<div class="hb-msg-acts" role="group" aria-label="reply actions"><button type="button" class="hb-msg-act" data-copy="${t.id}">${ICON.copy}copy</button><button type="button" class="hb-msg-act" data-redo>${ICON.redoMsg}redo</button></div>`
|
|
32
|
+
: "";
|
|
33
|
+
return (`<div class="hb-msg" data-turn="${t.id}"><span class="hb-msg-who"><span class="hb-msg-name">${esc(o.name)}</span>${t.stats ? `<span class="hb-msg-stats" title="${esc(t.stats)}">${esc(t.stats.replace(/ \((measured|inferred|vendor|unknown)\)$/, ""))}</span>` : ""}</span>` +
|
|
34
|
+
`${think}<div class="hb-msg-parts">${body}</div>${t.note ? `<span class="hb-msg-note">${esc(t.note)}</span>` : ""}${mem}${acts}</div>`);
|
|
35
|
+
}
|
|
36
|
+
/** The thread over a host, with the empty state inside it. */
|
|
37
|
+
export function mountChatPane(host, thread, o = {}) {
|
|
38
|
+
const name = o.name ?? "reply";
|
|
39
|
+
const l = listeners();
|
|
40
|
+
const draw = (s) => {
|
|
41
|
+
const sc = scroller(host);
|
|
42
|
+
const stick = pinned(sc);
|
|
43
|
+
if (!s.turns.length) {
|
|
44
|
+
host.innerHTML = `<div class="hb-lay-convempty"><h2 class="hb-lay-convempty-name">${esc(o.emptyName ?? "what are we working on?")}</h2>${o.emptyNote ? `<p class="hb-lay-convempty-note">${esc(o.emptyNote)}</p>` : ""}</div>`;
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
// keep folds a person opened open across redraws
|
|
48
|
+
const open = new Set([...host.querySelectorAll("details[open]")].map((d) => `${d.closest("[data-turn]")?.dataset.turn}:${d.className}`));
|
|
49
|
+
const last = s.turns[s.turns.length - 1];
|
|
50
|
+
host.innerHTML = s.turns.map((t) => turnHtml(t, { name, last: t === last, busy: s.busy })).join("");
|
|
51
|
+
for (const d of host.querySelectorAll("details")) {
|
|
52
|
+
if (open.has(`${d.closest("[data-turn]")?.dataset.turn}:${d.className}`))
|
|
53
|
+
d.open = true;
|
|
54
|
+
}
|
|
55
|
+
if (stick)
|
|
56
|
+
sc.scrollTop = sc.scrollHeight;
|
|
57
|
+
};
|
|
58
|
+
l.on(host, "click", (e) => {
|
|
59
|
+
const t = e.target;
|
|
60
|
+
const copy = t.closest("[data-copy]");
|
|
61
|
+
if (copy) {
|
|
62
|
+
const turn = thread.snapshot().turns.find((x) => String(x.id) === copy.dataset.copy);
|
|
63
|
+
if (turn)
|
|
64
|
+
void navigator.clipboard?.writeText(turn.text).then(() => (copy.lastChild.textContent = "copied")).catch(() => (copy.lastChild.textContent = "copy blocked"));
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (t.closest("[data-redo]"))
|
|
68
|
+
void thread.regenerate();
|
|
69
|
+
});
|
|
70
|
+
l.add(thread.subscribe(draw));
|
|
71
|
+
return { dispose: () => l.off() };
|
|
72
|
+
}
|
|
73
|
+
/** The composer: Enter sends (Shift Enter adds a line, Escape stops), send is the one pink, stop replaces it while a reply streams. */
|
|
74
|
+
export function mountComposer(host, thread, o = {}) {
|
|
75
|
+
host.innerHTML = `<form class="hb-convbox"><textarea rows="1" aria-label="${esc(o.label ?? "message")}" placeholder="${esc(o.placeholder ?? "say something")}"></textarea><span data-act></span></form>`;
|
|
76
|
+
const form = host.querySelector("form");
|
|
77
|
+
const area = host.querySelector("textarea");
|
|
78
|
+
const act = host.querySelector("[data-act]");
|
|
79
|
+
let busy = false;
|
|
80
|
+
const drawAct = () => {
|
|
81
|
+
act.innerHTML = busy ? `<button type="button" class="hb-btn" data-stop>stop</button>` : `<button type="submit" class="hb-btn hb-btn-go">send</button>`;
|
|
82
|
+
};
|
|
83
|
+
const send = () => {
|
|
84
|
+
const text = area.value.trim();
|
|
85
|
+
if (!text || busy)
|
|
86
|
+
return;
|
|
87
|
+
area.value = "";
|
|
88
|
+
autosize(area);
|
|
89
|
+
void thread.send(text);
|
|
90
|
+
};
|
|
91
|
+
const l = listeners();
|
|
92
|
+
l.on(form, "submit", (e) => {
|
|
93
|
+
e.preventDefault();
|
|
94
|
+
send();
|
|
95
|
+
});
|
|
96
|
+
l.on(act, "click", (e) => {
|
|
97
|
+
if (e.target.closest("[data-stop]"))
|
|
98
|
+
thread.stop();
|
|
99
|
+
});
|
|
100
|
+
l.on(area, "input", () => autosize(area));
|
|
101
|
+
l.on(area, "keydown", (e) => {
|
|
102
|
+
const k = composerKey(e, { busy, empty: !area.value, coarse: coarsePointer() });
|
|
103
|
+
if (k === "send") {
|
|
104
|
+
e.preventDefault();
|
|
105
|
+
send();
|
|
106
|
+
}
|
|
107
|
+
else if (k === "stop")
|
|
108
|
+
thread.stop();
|
|
109
|
+
});
|
|
110
|
+
l.add(thread.subscribe((s) => {
|
|
111
|
+
if (s.busy === busy && act.firstChild)
|
|
112
|
+
return;
|
|
113
|
+
busy = s.busy;
|
|
114
|
+
drawAct();
|
|
115
|
+
}));
|
|
116
|
+
return { dispose: () => l.off() };
|
|
117
|
+
}
|
|
118
|
+
/** The chat list rail (hackbuild-ui HbConversationList markup): new, open, rename, delete with a second press. */
|
|
119
|
+
export function mountChatList(host, list, o = {}) {
|
|
120
|
+
const l = listeners();
|
|
121
|
+
let armed = "";
|
|
122
|
+
let renaming = "";
|
|
123
|
+
const head = o.label ?? "chats";
|
|
124
|
+
const draw = (s) => {
|
|
125
|
+
host.innerHTML =
|
|
126
|
+
`<nav class="hb-convs" aria-label="${esc(head)}"><div class="hb-convs-hd"><span>${esc(head)}</span><button type="button" class="hb-convs-new" data-new aria-label="new chat">${ICON.plus}</button></div><ul class="hb-convs-list">` +
|
|
127
|
+
s.items
|
|
128
|
+
.map((c) => renaming === c.id
|
|
129
|
+
? `<li class="hb-convs-item"><form class="hb-convs-rename" data-rename="${esc(c.id)}"><input class="hb-input" aria-label="chat name" value="${esc(c.title)}"></form></li>`
|
|
130
|
+
: `<li class="hb-convs-item"${c.id === s.current ? ' aria-current="true"' : ""}><button type="button" class="hb-convs-open" data-open="${esc(c.id)}"><span class="hb-convs-title">${esc(c.title)}</span><span class="hb-convs-meta">${esc(listMeta({ updated: c.updated, count: c.count }))}</span></button><span class="hb-convs-acts"><button type="button" class="hb-convs-act" data-ren="${esc(c.id)}" aria-label="rename ${esc(c.title)}" title="rename">${ICON.pen}</button><button type="button" class="hb-convs-act is-del${armed === c.id ? " is-armed" : ""}" data-del="${esc(c.id)}" aria-label="${armed === c.id ? `press again to delete ${esc(c.title)}` : `delete ${esc(c.title)}`}">${armed === c.id ? "delete?" : ICON.trash}</button></span></li>`)
|
|
131
|
+
.join("") +
|
|
132
|
+
`</ul></nav>`;
|
|
133
|
+
host.querySelector(".hb-convs-rename input")?.focus();
|
|
134
|
+
};
|
|
135
|
+
const redraw = () => draw(list.snapshot());
|
|
136
|
+
l.on(host, "click", (e) => {
|
|
137
|
+
const t = e.target;
|
|
138
|
+
if (t.closest("[data-new]"))
|
|
139
|
+
return void list.create();
|
|
140
|
+
const open = t.closest("[data-open]")?.dataset.open;
|
|
141
|
+
if (open)
|
|
142
|
+
return list.open(open);
|
|
143
|
+
const ren = t.closest("[data-ren]")?.dataset.ren;
|
|
144
|
+
if (ren)
|
|
145
|
+
return ((renaming = ren), redraw());
|
|
146
|
+
const del = t.closest("[data-del]")?.dataset.del;
|
|
147
|
+
if (del) {
|
|
148
|
+
if (armed === del)
|
|
149
|
+
return ((armed = ""), list.remove(del));
|
|
150
|
+
armed = del;
|
|
151
|
+
redraw();
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
l.on(host, "submit", (e) => {
|
|
155
|
+
e.preventDefault();
|
|
156
|
+
const f = e.target.closest("[data-rename]");
|
|
157
|
+
if (f)
|
|
158
|
+
list.rename(f.dataset.rename, f.querySelector("input").value);
|
|
159
|
+
renaming = "";
|
|
160
|
+
redraw();
|
|
161
|
+
});
|
|
162
|
+
l.add(list.subscribe(draw));
|
|
163
|
+
return { dispose: () => l.off() };
|
|
164
|
+
}
|
|
165
|
+
/** The context meter (hackbuild-ui `.hb-ctxmeter`): what the next request carries against the model's context. */
|
|
166
|
+
export function mountContextMeter(host, thread, o = {}) {
|
|
167
|
+
const l = listeners();
|
|
168
|
+
const val = (v, d) => (typeof v === "function" ? v() : (v ?? d));
|
|
169
|
+
const draw = (s) => {
|
|
170
|
+
const use = contextUse(contextSegments(s, val(o.system, "")), val(o.budget, 4096));
|
|
171
|
+
host.innerHTML =
|
|
172
|
+
`<div class="hb-ctxmeter is-${use.tone}"><div class="hb-ctxmeter-hd"><span class="hb-ctxmeter-label">context</span><span class="hb-ctxmeter-words">${esc(use.words)}</span></div>` +
|
|
173
|
+
`<div class="hb-ctxmeter-bar" role="meter" aria-label="context used" aria-valuemin="0" aria-valuemax="${use.budget}" aria-valuenow="${use.used}" aria-valuetext="${esc(use.words)}">${use.rows.map((r, n) => `<i class="hb-ctxmeter-p${n % 6}" style="width:${Math.min(100, r.fraction * 100)}%"></i>`).join("")}</div>` +
|
|
174
|
+
`<ul class="hb-ctxmeter-legend">${use.rows.map((r, n) => `<li><i class="hb-ctxmeter-p${n % 6}" aria-hidden="true"></i>${esc(r.label)} <b>${r.tokens.toLocaleString("en-US")}</b></li>`).join("")}</ul></div>`;
|
|
175
|
+
};
|
|
176
|
+
l.add(thread.subscribe(draw));
|
|
177
|
+
return { dispose: () => l.off() };
|
|
178
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FrameView and CameraFeed: a
|
|
3
|
+
* frame in a hackbuild-ui camera tile with what the models found drawn
|
|
4
|
+
* over it (boxes with their word and score, landmark points and lines),
|
|
5
|
+
* a count in the corner and the caption under it. CameraFeed opens the
|
|
6
|
+
* camera into a tile and hands frames to the page at a set rate.
|
|
7
|
+
*/
|
|
8
|
+
import { type Mounted } from "./dom.js";
|
|
9
|
+
import { type FrameResults } from "./frame.js";
|
|
10
|
+
type Source = HTMLImageElement | HTMLVideoElement | HTMLCanvasElement;
|
|
11
|
+
/** A mounted frame view: set the source, the results to draw, mirroring, and paint again. */
|
|
12
|
+
export interface FrameView extends Mounted {
|
|
13
|
+
/** An image url, or a live element (a camera video); null shows the empty tile. */
|
|
14
|
+
setSource(src: string | Source | null): Promise<void>;
|
|
15
|
+
setResults(r: FrameResults): void;
|
|
16
|
+
setMirror(on: boolean): void;
|
|
17
|
+
/** Draw again, as after a resize or a new video frame. */
|
|
18
|
+
paint(): void;
|
|
19
|
+
}
|
|
20
|
+
/** Options for `mountFrameView`: empty words, mirroring and the colours of the drawn boxes. */
|
|
21
|
+
export interface FrameViewOptions {
|
|
22
|
+
empty?: string;
|
|
23
|
+
mirror?: boolean;
|
|
24
|
+
/** Ink of the drawn boxes' word strip; default the paper token. */
|
|
25
|
+
palette?: readonly string[];
|
|
26
|
+
}
|
|
27
|
+
/** Draws a frame in a camera tile on a host, with boxes, landmarks, a corner tag and a caption over it. */
|
|
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
|
+
*/
|
|
33
|
+
export interface CameraFeed extends Mounted {
|
|
34
|
+
start(): Promise<void>;
|
|
35
|
+
stop(): void;
|
|
36
|
+
readonly video: HTMLVideoElement;
|
|
37
|
+
readonly live: boolean;
|
|
38
|
+
subscribe(fn: (s: {
|
|
39
|
+
live: boolean;
|
|
40
|
+
error: string;
|
|
41
|
+
}) => void): () => void;
|
|
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
|
+
*/
|
|
47
|
+
export interface CameraFeedOptions {
|
|
48
|
+
/** Called with the video this many times a second while live. Default 4. */
|
|
49
|
+
fps?: number;
|
|
50
|
+
onFrame?: (video: HTMLVideoElement) => void | Promise<void>;
|
|
51
|
+
facingMode?: "user" | "environment";
|
|
52
|
+
/** Draw the video in a tile of its own; off when a FrameView shows it. */
|
|
53
|
+
tile?: boolean;
|
|
54
|
+
}
|
|
55
|
+
/** Opens the camera into a host and hands the video to `onFrame` at the set rate while it is live. */
|
|
56
|
+
export declare function mountCameraFeed(host: HTMLElement, o?: CameraFeedOptions): CameraFeed;
|
|
57
|
+
export {};
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FrameView and CameraFeed: a
|
|
3
|
+
* frame in a hackbuild-ui camera tile with what the models found drawn
|
|
4
|
+
* over it (boxes with their word and score, landmark points and lines),
|
|
5
|
+
* a count in the corner and the caption under it. CameraFeed opens the
|
|
6
|
+
* camera into a tile and hands frames to the page at a set rate.
|
|
7
|
+
*/
|
|
8
|
+
import { INSTANCE_COLOURS, cameraFault, closeCamera, openCamera } from "@virgilvox/hackbuild-ui/vanilla";
|
|
9
|
+
import { esc, listeners, show } from "./dom.js";
|
|
10
|
+
import { boxWords, fitMap, frameTag, labelColour, toView } from "./frame.js";
|
|
11
|
+
const css = (el, name, fb) => {
|
|
12
|
+
try {
|
|
13
|
+
return getComputedStyle(el).getPropertyValue(name).trim() || fb;
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return fb;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
/** Draws a frame in a camera tile on a host, with boxes, landmarks, a corner tag and a caption over it. */
|
|
20
|
+
export function mountFrameView(host, o = {}) {
|
|
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>`;
|
|
22
|
+
const fig = host.querySelector("figure");
|
|
23
|
+
const canvas = host.querySelector("canvas");
|
|
24
|
+
const none = host.querySelector(".hb-camtile-none");
|
|
25
|
+
const tag = host.querySelector(".hb-camtile-tag");
|
|
26
|
+
const cap = host.querySelector("[data-caption]");
|
|
27
|
+
const palette = o.palette ?? INSTANCE_COLOURS;
|
|
28
|
+
let src = null;
|
|
29
|
+
let results = {};
|
|
30
|
+
let mirror = !!o.mirror;
|
|
31
|
+
const l = listeners();
|
|
32
|
+
const size = () => {
|
|
33
|
+
const s = src;
|
|
34
|
+
if (!s)
|
|
35
|
+
return { w: 0, h: 0 };
|
|
36
|
+
if (s instanceof HTMLVideoElement)
|
|
37
|
+
return { w: s.videoWidth, h: s.videoHeight };
|
|
38
|
+
if (s instanceof HTMLImageElement)
|
|
39
|
+
return { w: s.naturalWidth, h: s.naturalHeight };
|
|
40
|
+
return { w: s.width, h: s.height };
|
|
41
|
+
};
|
|
42
|
+
const paint = () => {
|
|
43
|
+
const r = fig.getBoundingClientRect();
|
|
44
|
+
const dpr = Math.min(2, window.devicePixelRatio || 1);
|
|
45
|
+
canvas.width = Math.max(1, Math.round(r.width * dpr));
|
|
46
|
+
canvas.height = Math.max(1, Math.round(r.height * dpr));
|
|
47
|
+
const g = canvas.getContext("2d");
|
|
48
|
+
if (!g)
|
|
49
|
+
return;
|
|
50
|
+
g.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
51
|
+
g.clearRect(0, 0, r.width, r.height);
|
|
52
|
+
const sz = size();
|
|
53
|
+
const m = fitMap(sz, { w: r.width, h: r.height }, "cover");
|
|
54
|
+
if (src instanceof HTMLImageElement || src instanceof HTMLCanvasElement) {
|
|
55
|
+
g.save();
|
|
56
|
+
if (mirror) {
|
|
57
|
+
g.translate(r.width, 0);
|
|
58
|
+
g.scale(-1, 1);
|
|
59
|
+
}
|
|
60
|
+
g.drawImage(src, m.dx, m.dy, sz.w * m.scale, sz.h * m.scale);
|
|
61
|
+
g.restore();
|
|
62
|
+
}
|
|
63
|
+
const ink = css(fig, "--hb-void", "#0a0a0a");
|
|
64
|
+
const paper = css(fig, "--hb-paper", "ivory");
|
|
65
|
+
const slime = css(fig, "--hb-slime", "#a6e22e");
|
|
66
|
+
g.font = `11px ${css(fig, "--hb-utility", "ui-monospace, monospace")}`;
|
|
67
|
+
g.textBaseline = "top";
|
|
68
|
+
for (const b of results.boxes ?? []) {
|
|
69
|
+
const v = toView(b, m, r.width, mirror);
|
|
70
|
+
const c = labelColour(b.label, palette);
|
|
71
|
+
g.lineWidth = 3;
|
|
72
|
+
g.strokeStyle = ink;
|
|
73
|
+
g.strokeRect(v.x, v.y, v.w, v.h);
|
|
74
|
+
g.lineWidth = 2;
|
|
75
|
+
g.strokeStyle = c;
|
|
76
|
+
g.strokeRect(v.x, v.y, v.w, v.h);
|
|
77
|
+
const words = boxWords(b);
|
|
78
|
+
if (words) {
|
|
79
|
+
const tw = g.measureText(words).width + 8;
|
|
80
|
+
const ty = v.y >= 16 ? v.y - 16 : v.y;
|
|
81
|
+
g.fillStyle = c;
|
|
82
|
+
g.fillRect(v.x - 1, ty, tw, 16);
|
|
83
|
+
g.fillStyle = ink;
|
|
84
|
+
g.fillText(words, v.x + 3, ty + 2);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
for (const set of results.landmarks ?? []) {
|
|
88
|
+
const pts = set.points.map((p) => toView({ x: p.x, y: p.y, w: 0, h: 0 }, m, r.width, mirror));
|
|
89
|
+
g.strokeStyle = slime;
|
|
90
|
+
g.lineWidth = 1.5;
|
|
91
|
+
for (const [a, b] of set.edges ?? []) {
|
|
92
|
+
const pa = pts[a];
|
|
93
|
+
const pb = pts[b];
|
|
94
|
+
if (!pa || !pb)
|
|
95
|
+
continue;
|
|
96
|
+
g.beginPath();
|
|
97
|
+
g.moveTo(pa.x, pa.y);
|
|
98
|
+
g.lineTo(pb.x, pb.y);
|
|
99
|
+
g.stroke();
|
|
100
|
+
}
|
|
101
|
+
for (const p of pts) {
|
|
102
|
+
g.fillStyle = ink;
|
|
103
|
+
g.fillRect(p.x - 2.5, p.y - 2.5, 5, 5);
|
|
104
|
+
g.fillStyle = paper;
|
|
105
|
+
g.fillRect(p.x - 1.5, p.y - 1.5, 3, 3);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
const ro = typeof ResizeObserver === "function" ? new ResizeObserver(() => paint()) : null;
|
|
110
|
+
ro?.observe(fig);
|
|
111
|
+
l.add(() => ro?.disconnect());
|
|
112
|
+
let video = null;
|
|
113
|
+
let raf = 0;
|
|
114
|
+
const loop = () => {
|
|
115
|
+
paint();
|
|
116
|
+
raf = requestAnimationFrame(loop);
|
|
117
|
+
};
|
|
118
|
+
l.add(() => cancelAnimationFrame(raf));
|
|
119
|
+
const view = {
|
|
120
|
+
async setSource(s) {
|
|
121
|
+
cancelAnimationFrame(raf);
|
|
122
|
+
video?.remove();
|
|
123
|
+
video = null;
|
|
124
|
+
if (typeof s === "string") {
|
|
125
|
+
const img = new Image();
|
|
126
|
+
img.src = s;
|
|
127
|
+
await img.decode();
|
|
128
|
+
src = img;
|
|
129
|
+
}
|
|
130
|
+
else
|
|
131
|
+
src = s;
|
|
132
|
+
if (src instanceof HTMLVideoElement) {
|
|
133
|
+
// the video sits under the canvas; the canvas draws only the marks
|
|
134
|
+
video = src;
|
|
135
|
+
video.classList.add("hb-camtile-video");
|
|
136
|
+
fig.classList.toggle("is-mirror", mirror);
|
|
137
|
+
fig.prepend(video);
|
|
138
|
+
raf = requestAnimationFrame(loop);
|
|
139
|
+
}
|
|
140
|
+
show(none, !src);
|
|
141
|
+
const sz = size();
|
|
142
|
+
if (sz.w && sz.h)
|
|
143
|
+
fig.style.setProperty("--hb-camtile-ar", `${sz.w} / ${sz.h}`);
|
|
144
|
+
paint();
|
|
145
|
+
},
|
|
146
|
+
setResults(r) {
|
|
147
|
+
results = r;
|
|
148
|
+
const t = frameTag(r);
|
|
149
|
+
show(tag, !!t);
|
|
150
|
+
tag.textContent = t;
|
|
151
|
+
show(cap, !!r.caption);
|
|
152
|
+
cap.textContent = r.caption ?? "";
|
|
153
|
+
paint();
|
|
154
|
+
},
|
|
155
|
+
setMirror(on) {
|
|
156
|
+
mirror = on;
|
|
157
|
+
fig.classList.toggle("is-mirror", on && !!video);
|
|
158
|
+
paint();
|
|
159
|
+
},
|
|
160
|
+
paint,
|
|
161
|
+
dispose: () => l.off(),
|
|
162
|
+
};
|
|
163
|
+
return view;
|
|
164
|
+
}
|
|
165
|
+
/** Opens the camera into a host and hands the video to `onFrame` at the set rate while it is live. */
|
|
166
|
+
export function mountCameraFeed(host, o = {}) {
|
|
167
|
+
const video = document.createElement("video");
|
|
168
|
+
video.autoplay = true;
|
|
169
|
+
video.playsInline = true;
|
|
170
|
+
video.muted = true;
|
|
171
|
+
const tile = o.tile ?? true;
|
|
172
|
+
if (tile) {
|
|
173
|
+
host.innerHTML = `<figure class="hb-camtile is-mirror" aria-label="camera"><div class="hb-camtile-none" role="status">camera off</div></figure>`;
|
|
174
|
+
video.className = "hb-camtile-video";
|
|
175
|
+
host.querySelector("figure").prepend(video);
|
|
176
|
+
}
|
|
177
|
+
const none = host.querySelector(".hb-camtile-none");
|
|
178
|
+
let stream = null;
|
|
179
|
+
let timer = null;
|
|
180
|
+
let error = "";
|
|
181
|
+
let working = false;
|
|
182
|
+
const subs = new Set();
|
|
183
|
+
const emit = () => {
|
|
184
|
+
if (none) {
|
|
185
|
+
show(none, !stream);
|
|
186
|
+
none.textContent = error || "camera off";
|
|
187
|
+
host.querySelector("figure")?.classList.toggle("is-denied", !!error);
|
|
188
|
+
}
|
|
189
|
+
for (const fn of subs)
|
|
190
|
+
fn({ live: !!stream, error });
|
|
191
|
+
};
|
|
192
|
+
const feed = {
|
|
193
|
+
video,
|
|
194
|
+
get live() {
|
|
195
|
+
return !!stream;
|
|
196
|
+
},
|
|
197
|
+
async start() {
|
|
198
|
+
if (stream)
|
|
199
|
+
return;
|
|
200
|
+
error = "";
|
|
201
|
+
try {
|
|
202
|
+
stream = await openCamera({ facingMode: o.facingMode ?? "user", width: { ideal: 640 }, height: { ideal: 480 } });
|
|
203
|
+
video.srcObject = stream;
|
|
204
|
+
await video.play().catch(() => undefined);
|
|
205
|
+
timer = setInterval(() => {
|
|
206
|
+
if (working || !o.onFrame || video.readyState < 2)
|
|
207
|
+
return;
|
|
208
|
+
working = true;
|
|
209
|
+
void Promise.resolve(o.onFrame(video)).finally(() => (working = false));
|
|
210
|
+
}, 1000 / (o.fps ?? 4));
|
|
211
|
+
}
|
|
212
|
+
catch (e) {
|
|
213
|
+
error = cameraFault(e).text;
|
|
214
|
+
stream = null;
|
|
215
|
+
}
|
|
216
|
+
emit();
|
|
217
|
+
},
|
|
218
|
+
stop() {
|
|
219
|
+
if (timer)
|
|
220
|
+
clearInterval(timer);
|
|
221
|
+
timer = null;
|
|
222
|
+
closeCamera(stream);
|
|
223
|
+
stream = null;
|
|
224
|
+
video.srcObject = null;
|
|
225
|
+
emit();
|
|
226
|
+
},
|
|
227
|
+
subscribe(fn) {
|
|
228
|
+
subs.add(fn);
|
|
229
|
+
fn({ live: !!stream, error });
|
|
230
|
+
return () => subs.delete(fn);
|
|
231
|
+
},
|
|
232
|
+
dispose() {
|
|
233
|
+
feed.stop();
|
|
234
|
+
subs.clear();
|
|
235
|
+
},
|
|
236
|
+
};
|
|
237
|
+
emit();
|
|
238
|
+
return feed;
|
|
239
|
+
}
|