deictic 0.0.1 → 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 +144 -0
- package/dist/annotations/client.d.ts +4 -0
- package/dist/annotations/client.d.ts.map +1 -0
- package/dist/annotations/client.js +497 -0
- package/dist/annotations/client.js.map +1 -0
- package/dist/annotations/index.d.ts +110 -0
- package/dist/annotations/index.d.ts.map +1 -0
- package/dist/annotations/index.js +22 -0
- package/dist/annotations/index.js.map +1 -0
- package/dist/astro.d.ts +29 -0
- package/dist/astro.d.ts.map +1 -0
- package/dist/astro.js +24 -0
- package/dist/astro.js.map +1 -0
- package/dist/bun.d.ts +12 -0
- package/dist/bun.d.ts.map +1 -0
- package/dist/bun.js +67 -0
- package/dist/bun.js.map +1 -0
- package/dist/client/index.d.ts +93 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +1329 -0
- package/dist/client/index.js.map +1 -0
- package/dist/endpoints.js +354 -0
- package/dist/endpoints.js.map +1 -0
- package/dist/index.d.ts +220 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/index2.d.ts +23 -0
- package/dist/index3.d.ts +98 -0
- package/dist/index3.d.ts.map +1 -0
- package/dist/index4.d.ts +74 -0
- package/dist/index4.d.ts.map +1 -0
- package/dist/index5.d.ts +70 -0
- package/dist/index5.d.ts.map +1 -0
- package/dist/integration.d.ts +19 -0
- package/dist/integration.d.ts.map +1 -0
- package/dist/integration.js +277 -0
- package/dist/integration.js.map +1 -0
- package/dist/kept.js +23 -0
- package/dist/kept.js.map +1 -0
- package/dist/loader.d.ts +15 -0
- package/dist/loader.d.ts.map +1 -0
- package/dist/loader.js +17 -0
- package/dist/loader.js.map +1 -0
- package/dist/marks.js +14 -0
- package/dist/marks.js.map +1 -0
- package/dist/next.d.ts +17 -0
- package/dist/next.d.ts.map +1 -0
- package/dist/next.js +150 -0
- package/dist/next.js.map +1 -0
- package/dist/playwright.js +105 -0
- package/dist/playwright.js.map +1 -0
- package/dist/recommended/index.d.ts +25 -0
- package/dist/recommended/index.d.ts.map +1 -0
- package/dist/recommended/index.js +19 -0
- package/dist/recommended/index.js.map +1 -0
- package/dist/recordings/client.d.ts +4 -0
- package/dist/recordings/client.d.ts.map +1 -0
- package/dist/recordings/client.js +376 -0
- package/dist/recordings/client.js.map +1 -0
- package/dist/recordings/index.d.ts +2 -0
- package/dist/recordings/index.js +3 -0
- package/dist/recordings.js +235 -0
- package/dist/recordings.js.map +1 -0
- package/dist/screenshots/client.d.ts +23 -0
- package/dist/screenshots/client.d.ts.map +1 -0
- package/dist/screenshots/client.js +76 -0
- package/dist/screenshots/client.js.map +1 -0
- package/dist/screenshots/dom.d.ts +4 -0
- package/dist/screenshots/dom.d.ts.map +1 -0
- package/dist/screenshots/dom.js +92 -0
- package/dist/screenshots/dom.js.map +1 -0
- package/dist/screenshots/index.d.ts +2 -0
- package/dist/screenshots/index.js +98 -0
- package/dist/screenshots/index.js.map +1 -0
- package/dist/screenshots/rrweb.d.ts +9 -0
- package/dist/screenshots/rrweb.d.ts.map +1 -0
- package/dist/screenshots/rrweb.js +60 -0
- package/dist/screenshots/rrweb.js.map +1 -0
- package/dist/shortcut.js +63 -0
- package/dist/shortcut.js.map +1 -0
- package/dist/tailwind/client.d.ts +4 -0
- package/dist/tailwind/client.d.ts.map +1 -0
- package/dist/tailwind/client.js +613 -0
- package/dist/tailwind/client.js.map +1 -0
- package/dist/tailwind/index.d.ts +2 -0
- package/dist/tailwind/index.js +557 -0
- package/dist/tailwind/index.js.map +1 -0
- package/dist/tasks/client.d.ts +6 -0
- package/dist/tasks/client.d.ts.map +1 -0
- package/dist/tasks/client.js +642 -0
- package/dist/tasks/client.js.map +1 -0
- package/dist/tasks/index.d.ts +159 -0
- package/dist/tasks/index.d.ts.map +1 -0
- package/dist/tasks/index.js +348 -0
- package/dist/tasks/index.js.map +1 -0
- package/dist/vite.d.ts +17 -0
- package/dist/vite.d.ts.map +1 -0
- package/dist/vite.js +44 -0
- package/dist/vite.js.map +1 -0
- package/dist/voice/client.d.ts +4 -0
- package/dist/voice/client.d.ts.map +1 -0
- package/dist/voice/client.js +66 -0
- package/dist/voice/client.js.map +1 -0
- package/dist/voice/index.d.ts +47 -0
- package/dist/voice/index.d.ts.map +1 -0
- package/dist/voice/index.js +74 -0
- package/dist/voice/index.js.map +1 -0
- package/dist/waveform.js +93 -0
- package/dist/waveform.js.map +1 -0
- package/dist/webpack.d.ts +50 -0
- package/dist/webpack.d.ts.map +1 -0
- package/dist/webpack.js +78 -0
- package/dist/webpack.js.map +1 -0
- package/package.json +307 -7
- package/skills/deictic/SKILL.md +47 -0
- package/skills/deictic/references/install.md +81 -0
- package/skills/deictic/references/recordings.md +83 -0
- package/skills/deictic/references/tasks.md +79 -0
- package/skills/deictic/references/watch.md +43 -0
- package/skills/deictic/scripts/frame.mjs +62 -0
- package/skills/deictic/scripts/lib.mjs +193 -0
- package/skills/deictic/scripts/recording.mjs +186 -0
- package/skills/deictic/scripts/task.mjs +84 -0
- package/skills/deictic/scripts/transcribe.mjs +93 -0
- package/skills/deictic/scripts/voice.mjs +50 -0
- package/skills/deictic/scripts/watch.mjs +51 -0
- package/src/astro.ts +34 -0
- package/src/bun.ts +79 -0
- package/src/client/index.ts +833 -0
- package/src/client/lightbox.ts +256 -0
- package/src/client/style.ts +243 -0
- package/src/client/tooltip.ts +78 -0
- package/src/client/waveform.ts +98 -0
- package/src/index.ts +240 -0
- package/src/loader.ts +28 -0
- package/src/next.ts +133 -0
- package/src/plugins/annotations/client.ts +301 -0
- package/src/plugins/annotations/draw.ts +169 -0
- package/src/plugins/annotations/index.ts +105 -0
- package/src/plugins/annotations/svg.ts +61 -0
- package/src/plugins/recommended/index.ts +35 -0
- package/src/plugins/recordings/client.ts +315 -0
- package/src/plugins/recordings/index.ts +174 -0
- package/src/plugins/recordings/marks.ts +11 -0
- package/src/plugins/recordings/ours.ts +70 -0
- package/src/plugins/recordings/replay.ts +139 -0
- package/src/plugins/screenshots/client.ts +63 -0
- package/src/plugins/screenshots/dom.ts +79 -0
- package/src/plugins/screenshots/index.ts +194 -0
- package/src/plugins/screenshots/playwright.ts +119 -0
- package/src/plugins/screenshots/rrweb.ts +45 -0
- package/src/plugins/tailwind/catalog.ts +396 -0
- package/src/plugins/tailwind/client.ts +669 -0
- package/src/plugins/tailwind/index.ts +267 -0
- package/src/plugins/tasks/client.ts +622 -0
- package/src/plugins/tasks/index.ts +513 -0
- package/src/plugins/voice/client.ts +57 -0
- package/src/plugins/voice/index.ts +114 -0
- package/src/shortcut.ts +83 -0
- package/src/tools/astro.ts +81 -0
- package/src/tools/editor.ts +22 -0
- package/src/tools/endpoints.ts +163 -0
- package/src/tools/history.ts +203 -0
- package/src/tools/integration.ts +106 -0
- package/src/tools/kept.ts +21 -0
- package/src/tools/locate.ts +94 -0
- package/src/tools/plugins.ts +41 -0
- package/src/tools/source.ts +72 -0
- package/src/vite.ts +62 -0
- package/src/webpack.ts +107 -0
- package/index.js +0 -1
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Watching for tasks
|
|
2
|
+
|
|
3
|
+
The point is that a task left in the page gets worked without anyone prompting you. Use whatever your harness has
|
|
4
|
+
for being woken by a command's output; between tasks, never sleep-poll in the foreground.
|
|
5
|
+
|
|
6
|
+
`<skill>` below is this skill's folder; `deictic` is the channel (pass yours if the config sets another).
|
|
7
|
+
|
|
8
|
+
## With a monitor (Claude Code's Monitor, or any tool that turns each output line into an event)
|
|
9
|
+
|
|
10
|
+
Run `node <skill>/scripts/watch.mjs deictic` as the monitor, with the longest timeout it allows, and start it again
|
|
11
|
+
when it expires. It prints, one line each:
|
|
12
|
+
|
|
13
|
+
- `ready: #68 …` for each task already waiting as it starts;
|
|
14
|
+
- `new task #71: "Make it bolder" at src/App.tsx:12:5 on /`;
|
|
15
|
+
- `reply on #71 by krtgo: …`: an answer to your question, or more to do on a task;
|
|
16
|
+
- `task #71 canceled: …`: the person undid it in the page; stop, and put back what you changed for it;
|
|
17
|
+
- `watch ended …`: the board went away; check `vb whoami`, then start it again.
|
|
18
|
+
|
|
19
|
+
On an event, work the task ([tasks.md](tasks.md)) while the monitor keeps running. Ignore replies you wrote yourself.
|
|
20
|
+
|
|
21
|
+
## With a background command that exits (one wake-up per task)
|
|
22
|
+
|
|
23
|
+
Where you're notified when a background command ends but can't stream events, run in the background:
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
vb tasks claim --ready deictic --wait 30m --lease 30m
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
It blocks until a task is ready, claims it and prints it, and exits; it exits 1 with nothing claimed after 30
|
|
30
|
+
minutes. Work the task, then start it again. To be woken without claiming (to answer replies too):
|
|
31
|
+
`vb wait deictic --label deictic.at --timeout 30m`.
|
|
32
|
+
|
|
33
|
+
## Without either
|
|
34
|
+
|
|
35
|
+
Run that same `vb tasks claim --ready deictic --wait 30m` in the foreground at the end of each task: your turn
|
|
36
|
+
waits for the next one. Tell the person that's how you're waiting, as it holds the session.
|
|
37
|
+
|
|
38
|
+
## Things to know
|
|
39
|
+
|
|
40
|
+
- A claim is a lease (15 minutes unless `--lease`, at most 1h). For longer work, `vb tasks renew <id>`.
|
|
41
|
+
- `vb tasks deictic` lists what's open; `--state ready` what's waiting.
|
|
42
|
+
- Several agents can watch one channel: a claim is what keeps two from taking the same task.
|
|
43
|
+
- Undo in the page cancels a task only while no one has claimed it; after that the person replies instead.
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Screenshots of a recording at moments of it, as its replay page shows them (marks and pointer included),
|
|
3
|
+
// at the recorded viewport's size. By default: just after each change to the marks, and the end.
|
|
4
|
+
// Usage: frame.mjs <task | replay URL | recording ID | file> [--at 4.2 ...] [--every 2] [--out dir] [--base url]
|
|
5
|
+
// Needs the dev server running (it serves the replay) and Playwright (playwright-core or playwright) in the project.
|
|
6
|
+
import { mkdirSync } from 'node:fs';
|
|
7
|
+
import { tmpdir } from 'node:os';
|
|
8
|
+
import { join, resolve } from 'node:path';
|
|
9
|
+
|
|
10
|
+
import { clock, fail, fromProject, loadRecording, parseArgs } from './lib.mjs';
|
|
11
|
+
|
|
12
|
+
const { options, rest } = parseArgs(process.argv.slice(2));
|
|
13
|
+
const { kept, id, replay } = await loadRecording(rest[0], Number(options.nth?.[0] ?? 1));
|
|
14
|
+
const base = options.base?.[0];
|
|
15
|
+
// The replay is served by the dev server that recorded it, under deictic's routes.
|
|
16
|
+
const page = base
|
|
17
|
+
? `${base.replace(/\/$/, '')}/__deictic/plugins/recordings/replay/${id}`
|
|
18
|
+
: (replay ?? `${new URL(kept.page).origin}/__deictic/plugins/recordings/replay/${id}`);
|
|
19
|
+
|
|
20
|
+
const t0 = kept.events[0].timestamp;
|
|
21
|
+
let times = (options.at ?? []).map(Number);
|
|
22
|
+
if (options.every) for (let t = 0; t <= kept.duration / 1000; t += Number(options.every[0])) times.push(t);
|
|
23
|
+
if (times.length === 0) {
|
|
24
|
+
// Just after each change to the marks, so it's drawn, then the end.
|
|
25
|
+
const marks = kept.events.filter((e) => e.type === 5 && e.data.tag === 'deictic.annotations' && (e.data.payload.svg ?? '') !== '');
|
|
26
|
+
times = [...marks.map((e) => (e.timestamp - t0 + 50) / 1000), kept.duration / 1000];
|
|
27
|
+
}
|
|
28
|
+
times = [...new Set(times.map((t) => Math.min(Math.max(0, t), kept.duration / 1000)))].sort((a, b) => a - b);
|
|
29
|
+
if (times.some((t) => !Number.isFinite(t))) fail('--at and --every take seconds: --at 4.2');
|
|
30
|
+
|
|
31
|
+
const out = resolve(options.out?.[0] ?? join(tmpdir(), 'deictic-frames', id));
|
|
32
|
+
mkdirSync(out, { recursive: true });
|
|
33
|
+
|
|
34
|
+
const { chromium } = await fromProject('playwright-core', 'playwright');
|
|
35
|
+
let browser;
|
|
36
|
+
for (const channel of [undefined, 'chrome', 'msedge']) {
|
|
37
|
+
try {
|
|
38
|
+
browser = await chromium.launch(channel ? { channel } : {});
|
|
39
|
+
break;
|
|
40
|
+
} catch {}
|
|
41
|
+
}
|
|
42
|
+
if (browser === undefined) fail('No Chromium to launch: npx playwright install chromium, or install Chrome or Edge.');
|
|
43
|
+
try {
|
|
44
|
+
// `bare`: the replay alone, at the recorded size, so a window that size shows it 1:1.
|
|
45
|
+
const view = await browser.newPage({ viewport: kept.viewport });
|
|
46
|
+
for (const t of times) {
|
|
47
|
+
const url = new URL(page);
|
|
48
|
+
url.searchParams.set('t', t.toFixed(2));
|
|
49
|
+
url.searchParams.set('bare', '');
|
|
50
|
+
const res = await view.goto(url.href);
|
|
51
|
+
if (!res?.ok()) fail(`${url.href}: ${res?.status()}. Is the dev server running? Pass --base with its URL.`);
|
|
52
|
+
await view.waitForSelector('body[data-ready]', { timeout: 15_000 });
|
|
53
|
+
// The replayed page's images and fonts.
|
|
54
|
+
await view.waitForLoadState('networkidle').catch(() => {});
|
|
55
|
+
await view.waitForTimeout(200);
|
|
56
|
+
const path = join(out, `${String(Math.round(t * 1000)).padStart(6, '0')}.png`);
|
|
57
|
+
await view.screenshot({ path });
|
|
58
|
+
console.log(`${clock(t * 1000).padStart(6)} ${path}`);
|
|
59
|
+
}
|
|
60
|
+
} finally {
|
|
61
|
+
await browser.close();
|
|
62
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// What the scripts share: the board's CLI, the project's `.deictic/` folders, and finding a recording or a
|
|
2
|
+
// voice clip by a task's ID, a recording's ID, a replay URL or a path. Node 20 or Bun; no dependencies.
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import { existsSync, mkdtempSync, readdirSync, readFileSync } from 'node:fs';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { delimiter, dirname, join, resolve } from 'node:path';
|
|
7
|
+
import { pathToFileURL } from 'node:url';
|
|
8
|
+
|
|
9
|
+
/** `--name value` and `--flag` options, and the arguments around them. */
|
|
10
|
+
export function parseArgs(argv, flags = []) {
|
|
11
|
+
const options = {};
|
|
12
|
+
const rest = [];
|
|
13
|
+
for (let i = 0; i < argv.length; i++) {
|
|
14
|
+
const a = argv[i];
|
|
15
|
+
if (!a.startsWith('--')) rest.push(a);
|
|
16
|
+
else if (flags.includes(a.slice(2))) options[a.slice(2)] = true;
|
|
17
|
+
else (options[a.slice(2)] ??= []).push(argv[++i]);
|
|
18
|
+
}
|
|
19
|
+
return { options, rest };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function fail(message) {
|
|
23
|
+
console.error(message);
|
|
24
|
+
process.exit(1);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** `1:02.5`, from milliseconds. */
|
|
28
|
+
export function clock(ms) {
|
|
29
|
+
const s = Math.max(0, ms) / 1000;
|
|
30
|
+
return `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, '0')}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** This directory and each above it. */
|
|
34
|
+
function* upFrom(dir = process.cwd()) {
|
|
35
|
+
for (let at = resolve(dir); ; at = dirname(at)) {
|
|
36
|
+
yield at;
|
|
37
|
+
if (dirname(at) === at) return;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Every `.deictic/` near here: in this directory or above, or in a folder of it (a site/, an app/). */
|
|
42
|
+
export function deicticDirs() {
|
|
43
|
+
const found = [...upFrom()].map((d) => join(d, '.deictic')).filter((p) => existsSync(p));
|
|
44
|
+
const walk = (dir, depth) => {
|
|
45
|
+
if (depth === 0) return;
|
|
46
|
+
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
47
|
+
if (!e.isDirectory() || e.name === 'node_modules' || (e.name.startsWith('.') && e.name !== '.deictic')) continue;
|
|
48
|
+
const path = join(dir, e.name);
|
|
49
|
+
if (e.name === '.deictic') found.push(path);
|
|
50
|
+
else walk(path, depth - 1);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
walk(process.cwd(), 3);
|
|
54
|
+
return [...new Set(found)];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* How to run the board's CLI: `vb` from the project's dependencies or the PATH, with the environment's board,
|
|
59
|
+
* as `spawn`'s command, arguments and options.
|
|
60
|
+
*/
|
|
61
|
+
export function vbCommand(args) {
|
|
62
|
+
const bins = [...upFrom()].map((d) => join(d, 'node_modules', '.bin'));
|
|
63
|
+
const env = { ...process.env, PATH: [...bins, process.env.PATH].join(delimiter) };
|
|
64
|
+
// npm's shims on Windows are .cmd files, which only a shell runs; the arguments here are IDs and names.
|
|
65
|
+
if (process.platform === 'win32') return [`vb ${args.map((a) => `"${a}"`).join(' ')}`, [], { env, shell: true }];
|
|
66
|
+
return ['vb', args, { env }];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Runs the board's CLI and answers what it printed: parsed with `json`, bytes for a download to stdout. */
|
|
70
|
+
export function vb(args, { json = false } = {}) {
|
|
71
|
+
const [command, argv, options] = vbCommand(json ? [...args, '--json'] : args);
|
|
72
|
+
const run = spawnSync(command, argv, {
|
|
73
|
+
...options,
|
|
74
|
+
encoding: json || args[0] !== 'download' ? 'utf8' : 'buffer',
|
|
75
|
+
maxBuffer: 1 << 28,
|
|
76
|
+
});
|
|
77
|
+
if (run.error) fail(`vb: ${run.error.message}. Install @vercel/board in the project, or put vb on the PATH.`);
|
|
78
|
+
if (run.status !== 0) fail(`vb ${args.join(' ')}: ${String(run.stderr).trim() || `exit ${run.status}`}`);
|
|
79
|
+
return json ? JSON.parse(run.stdout) : run.stdout;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** A task's root message, by its ID (`68` or `#68`). */
|
|
83
|
+
export const task = (id) => vb(['read', String(id).replace(/^#/, '')], { json: true }).message;
|
|
84
|
+
|
|
85
|
+
/** An attachment's bytes. */
|
|
86
|
+
export const download = (attachment) => vb(['download', attachment.id, '-']);
|
|
87
|
+
|
|
88
|
+
const TASK = /^#?\d+$/;
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* A recording, with where it came from: `{ kept, id, replay?, task? }`. `ref` is a task's ID (its first
|
|
92
|
+
* recording, or the `nth`), a replay or recording URL, a recording's ID kept under a `.deictic/`, or a path.
|
|
93
|
+
*/
|
|
94
|
+
export async function loadRecording(ref, nth = 1) {
|
|
95
|
+
if (ref === undefined) fail('Name a recording: a task (68), a replay URL, a recording ID or a JSON file.');
|
|
96
|
+
if (TASK.test(ref)) {
|
|
97
|
+
const root = task(ref);
|
|
98
|
+
const files = root.attachments.filter((a) => /^recording-.*\.json$/.test(a.name));
|
|
99
|
+
const file = files[nth - 1];
|
|
100
|
+
if (file === undefined) fail(`Task #${root.id} has ${files.length} recording(s), not a ${nth}th.`);
|
|
101
|
+
const kept = JSON.parse(download(file).toString('utf8'));
|
|
102
|
+
const id = file.name.slice('recording-'.length, -'.json'.length);
|
|
103
|
+
const replay = root.text.match(new RegExp(`https?://\\S+/replay/${id}`))?.[0];
|
|
104
|
+
return { kept, id, replay, task: root };
|
|
105
|
+
}
|
|
106
|
+
if (/^https?:/.test(ref)) {
|
|
107
|
+
const url = new URL(ref);
|
|
108
|
+
const id = url.pathname.split('/').at(-1);
|
|
109
|
+
const json = new URL(url.pathname.replace(/\/(replay|recording)\/[^/]+$/, `/recording/${id}`), url);
|
|
110
|
+
const res = await fetch(json);
|
|
111
|
+
if (!res.ok) fail(`${json}: ${res.status} ${await res.text()}`);
|
|
112
|
+
return { kept: await res.json(), id, replay: new URL(json.pathname.replace(/\/recording\//, '/replay/'), url).href };
|
|
113
|
+
}
|
|
114
|
+
if (existsSync(ref)) return { kept: JSON.parse(readFileSync(ref, 'utf8')), id: ref.replace(/^.*[\\/]|\.json$/g, '') };
|
|
115
|
+
for (const dir of deicticDirs()) {
|
|
116
|
+
const path = join(dir, 'recordings', `${ref}.json`);
|
|
117
|
+
if (existsSync(path)) return { kept: JSON.parse(readFileSync(path, 'utf8')), id: ref };
|
|
118
|
+
}
|
|
119
|
+
fail(`No recording ${ref} in ${deicticDirs().join(', ') || 'any .deictic/ near here'}: name its task or replay URL instead.`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** A voice clip's audio as a file: kept under a `.deictic/`, or downloaded from `fromTask` to a temporary folder. */
|
|
123
|
+
export function voiceFile(id, fromTask) {
|
|
124
|
+
for (const dir of deicticDirs()) {
|
|
125
|
+
const voice = join(dir, 'voice');
|
|
126
|
+
const name = existsSync(voice) ? readdirSync(voice).find((f) => f.startsWith(`${id}.`)) : undefined;
|
|
127
|
+
if (name !== undefined) return join(voice, name);
|
|
128
|
+
}
|
|
129
|
+
const file = fromTask?.attachments.find((a) => a.name.startsWith(`voice-${id}.`));
|
|
130
|
+
if (file === undefined) fail(`No voice clip ${id} here${fromTask ? ` or on task #${fromTask.id}` : ''}.`);
|
|
131
|
+
const path = join(mkdtempSync(join(tmpdir(), 'deictic-voice-')), file.name);
|
|
132
|
+
// The CLI writes an attachment to a path of our choosing.
|
|
133
|
+
vb(['download', file.id, path]);
|
|
134
|
+
return path;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The voice clips `ref` names, each `{ id, file, at, recording? }`: `at` is where it starts in its recording (0
|
|
139
|
+
* for a voice note on its own). `ref` is a task (every recording's clips and its voice notes), a recording as
|
|
140
|
+
* `loadRecording` takes one, or a clip's ID.
|
|
141
|
+
*/
|
|
142
|
+
export async function voiceClips(ref) {
|
|
143
|
+
if (ref === undefined) fail('Name a task, a recording or a voice clip.');
|
|
144
|
+
const clips = [];
|
|
145
|
+
if (TASK.test(ref)) {
|
|
146
|
+
const root = task(ref);
|
|
147
|
+
const recordings = root.attachments.filter((a) => /^recording-.*\.json$/.test(a.name));
|
|
148
|
+
const inRecordings = new Set();
|
|
149
|
+
for (let n = 1; n <= recordings.length; n++) {
|
|
150
|
+
const { kept, id } = await loadRecording(ref, n);
|
|
151
|
+
for (const c of kept.voice ?? []) {
|
|
152
|
+
inRecordings.add(c.id);
|
|
153
|
+
clips.push({ id: c.id, file: voiceFile(c.id, root), at: c.at, recording: id });
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
for (const a of root.attachments) {
|
|
157
|
+
const id = a.name.match(/^voice-(.+)\.\w+$/)?.[1];
|
|
158
|
+
if (id !== undefined && !inRecordings.has(id)) clips.push({ id, file: voiceFile(id, root), at: 0 });
|
|
159
|
+
}
|
|
160
|
+
} else if (!/^https?:/.test(ref) && !existsSync(ref) && isClip(ref)) {
|
|
161
|
+
clips.push({ id: ref, file: voiceFile(ref), at: 0 });
|
|
162
|
+
} else {
|
|
163
|
+
const { kept, id } = await loadRecording(ref);
|
|
164
|
+
for (const c of kept.voice ?? []) clips.push({ id: c.id, file: voiceFile(c.id), at: c.at, recording: id });
|
|
165
|
+
}
|
|
166
|
+
if (clips.length === 0) fail(`No voice on ${ref}.`);
|
|
167
|
+
return clips;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const isClip = (id) =>
|
|
171
|
+
deicticDirs().some((d) => existsSync(join(d, 'voice')) && readdirSync(join(d, 'voice')).some((f) => f.startsWith(`${id}.`)));
|
|
172
|
+
|
|
173
|
+
/** Runs ffmpeg, which reads what MediaRecorder makes; its log is on stderr. */
|
|
174
|
+
export function ffmpeg(args, encoding = 'utf8') {
|
|
175
|
+
const run = spawnSync('ffmpeg', ['-hide_banner', '-nostats', ...args], { encoding, maxBuffer: 1 << 30 });
|
|
176
|
+
if (run.error) fail('Needs ffmpeg on the PATH (https://ffmpeg.org/download.html).');
|
|
177
|
+
return run;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** The project's own copy of a package, where a script needs one it doesn't bundle (Playwright). */
|
|
181
|
+
export async function fromProject(...names) {
|
|
182
|
+
for (const dir of upFrom()) {
|
|
183
|
+
for (const name of names) {
|
|
184
|
+
const pkg = join(dir, 'node_modules', name, 'package.json');
|
|
185
|
+
if (!existsSync(pkg)) continue;
|
|
186
|
+
const { exports, main } = JSON.parse(readFileSync(pkg, 'utf8'));
|
|
187
|
+
const entry = exports?.['.']?.import ?? exports?.['.']?.default ?? main ?? 'index.js';
|
|
188
|
+
const path = join(dirname(pkg), typeof entry === 'string' ? entry : (entry.default ?? 'index.js'));
|
|
189
|
+
return import(pathToFileURL(path).href);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return fail(`Needs ${names.join(' or ')} in the project: npm install -D ${names[0]}`);
|
|
193
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// A recording as a timeline: the page, each click and field typed in (with the element's place in the source),
|
|
3
|
+
// scrolls, resizes, each change to the marks (what was drawn, where, and the notes' text), the voice clips,
|
|
4
|
+
// and the end. Usage: recording.mjs <task | replay URL | recording ID | file> [--nth 2] [--json]
|
|
5
|
+
import { clock, fail, loadRecording, parseArgs } from './lib.mjs';
|
|
6
|
+
|
|
7
|
+
const { options, rest } = parseArgs(process.argv.slice(2), ['json']);
|
|
8
|
+
const { kept, id, replay, task } = await loadRecording(rest[0], Number(options.nth?.[0] ?? 1));
|
|
9
|
+
const { events } = kept;
|
|
10
|
+
if (!Array.isArray(events) || events.length === 0) fail(`Recording ${id} has no events.`);
|
|
11
|
+
const t0 = events[0].timestamp;
|
|
12
|
+
|
|
13
|
+
// The page's nodes by rrweb's IDs, from the full snapshot and each mutation: enough to name an element.
|
|
14
|
+
const nodes = new Map();
|
|
15
|
+
const add = (node, parent) => {
|
|
16
|
+
nodes.set(node.id, { ...node, parent, childNodes: undefined, kids: (node.childNodes ?? []).map((c) => c.id) });
|
|
17
|
+
for (const c of node.childNodes ?? []) add(c, node.id);
|
|
18
|
+
};
|
|
19
|
+
const textOf = (nid, max = 60) => {
|
|
20
|
+
let out = '';
|
|
21
|
+
const walk = (n) => {
|
|
22
|
+
const node = nodes.get(n);
|
|
23
|
+
if (node === undefined || out.length > max) return;
|
|
24
|
+
if (node.type === 3) out += node.textContent ?? '';
|
|
25
|
+
for (const k of node.kids ?? []) walk(k);
|
|
26
|
+
};
|
|
27
|
+
walk(nid);
|
|
28
|
+
const text = out.replace(/\s+/g, ' ').trim();
|
|
29
|
+
return text.length > max ? `${text.slice(0, max)}…` : text;
|
|
30
|
+
};
|
|
31
|
+
/** `<button> "Save" at src/App.tsx:9:7`: the element, its text, and the nearest place deictic marked. */
|
|
32
|
+
const describe = (nid) => {
|
|
33
|
+
const node = nodes.get(nid);
|
|
34
|
+
if (node === undefined) return `node ${nid}`;
|
|
35
|
+
if (node.type === 0) return 'the page';
|
|
36
|
+
let at;
|
|
37
|
+
for (let n = node; n !== undefined && at === undefined; n = nodes.get(n.parent)) at = n.attributes?.['data-deictic'];
|
|
38
|
+
const tag = node.tagName ? `<${node.tagName}>` : 'text';
|
|
39
|
+
const text = textOf(nid);
|
|
40
|
+
return `${tag}${text ? ` "${text}"` : ''}${at ? ` at ${at}` : ''}`;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
// The marks, as data where the recording has it, else read off the SVG.
|
|
44
|
+
const boundsOf = (points) => {
|
|
45
|
+
const xs = points.map((p) => p.x);
|
|
46
|
+
const ys = points.map((p) => p.y);
|
|
47
|
+
return `(${Math.round(Math.min(...xs))},${Math.round(Math.min(...ys))})–(${Math.round(Math.max(...xs))},${Math.round(Math.max(...ys))})`;
|
|
48
|
+
};
|
|
49
|
+
const shapeOf = ({ shape }) => {
|
|
50
|
+
switch (shape.kind) {
|
|
51
|
+
case 'box':
|
|
52
|
+
return `box ${boundsOf([shape, { x: shape.x + shape.width, y: shape.y + shape.height }])}`;
|
|
53
|
+
case 'arrow':
|
|
54
|
+
return `arrow from (${Math.round(shape.from.x)},${Math.round(shape.from.y)}) to (${Math.round(shape.to.x)},${Math.round(shape.to.y)})`;
|
|
55
|
+
case 'pen':
|
|
56
|
+
return `pen stroke over ${boundsOf(shape.points)}`;
|
|
57
|
+
case 'note':
|
|
58
|
+
return `note at (${Math.round(shape.at.x)},${Math.round(shape.at.y)}): ${JSON.stringify(shape.text)}`;
|
|
59
|
+
default:
|
|
60
|
+
return shape.kind;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const pairs = (s) => [...s.matchAll(/(-?[\d.]+)[ ,](-?[\d.]+)/g)].map((m) => ({ x: Number(m[1]), y: Number(m[2]) }));
|
|
64
|
+
const shapesInSvg = (svg) => {
|
|
65
|
+
const out = [];
|
|
66
|
+
const unescape = (t) => t.replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll('&', '&');
|
|
67
|
+
for (const m of svg.matchAll(/<(rect|path|polyline|text)\b([^>]*)>(?:(.*?)<\/text>)?/g)) {
|
|
68
|
+
const [, tag, attrs, inner] = m;
|
|
69
|
+
const num = (name) => Number(attrs.match(new RegExp(`\\b${name}="(-?[\\d.]+)"`))?.[1]);
|
|
70
|
+
if (tag === 'rect' && attrs.includes('fill="none"'))
|
|
71
|
+
out.push({ shape: { kind: 'box', x: num('x'), y: num('y'), width: num('width'), height: num('height') } });
|
|
72
|
+
if (tag === 'path') {
|
|
73
|
+
const [from, to] = pairs(attrs.match(/d="([^"]*)"/)[1]);
|
|
74
|
+
out.push({ shape: { kind: 'arrow', from, to } });
|
|
75
|
+
}
|
|
76
|
+
if (tag === 'polyline') out.push({ shape: { kind: 'pen', points: pairs(attrs.match(/points="([^"]*)"/)[1]) } });
|
|
77
|
+
if (tag === 'text') {
|
|
78
|
+
const lines = [...inner.matchAll(/<tspan[^>]*>(.*?)<\/tspan>/g)].map((l) => unescape(l[1]));
|
|
79
|
+
const at = pairs(
|
|
80
|
+
inner
|
|
81
|
+
.match(/x="(-?[\d.]+)" y="(-?[\d.]+)"/)
|
|
82
|
+
?.slice(1)
|
|
83
|
+
.join(',') ?? '0,0',
|
|
84
|
+
)[0];
|
|
85
|
+
out.push({ shape: { kind: 'note', at, text: lines.join('\n') } });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return out;
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const timeline = [];
|
|
92
|
+
const at = (e) => e.timestamp - t0;
|
|
93
|
+
const push = (t, kind, text, extra = {}) => timeline.push({ t, at: clock(t), kind, text, ...extra });
|
|
94
|
+
let marks = [];
|
|
95
|
+
let scroll;
|
|
96
|
+
let typing;
|
|
97
|
+
const flushScroll = () => {
|
|
98
|
+
if (scroll) push(scroll.t, 'scroll', `${describe(scroll.id)} to (${scroll.x},${scroll.y})`);
|
|
99
|
+
scroll = undefined;
|
|
100
|
+
};
|
|
101
|
+
const flushTyping = () => {
|
|
102
|
+
if (typing) push(typing.t, 'input', `${describe(typing.id)}: ${typing.value}`);
|
|
103
|
+
typing = undefined;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
for (const e of events) {
|
|
107
|
+
const t = at(e);
|
|
108
|
+
if (e.type === 4) push(t, 'page', `${e.data.href} at ${e.data.width}×${e.data.height}`);
|
|
109
|
+
if (e.type === 2) {
|
|
110
|
+
nodes.clear();
|
|
111
|
+
add(e.data.node, undefined);
|
|
112
|
+
}
|
|
113
|
+
if (e.type === 5 && e.data.tag === 'deictic.annotations') {
|
|
114
|
+
const now = e.data.payload.annotations ?? shapesInSvg(e.data.payload.svg ?? '');
|
|
115
|
+
const key = (a) => a.id ?? JSON.stringify(a.shape);
|
|
116
|
+
const before = new Set(marks.map(key));
|
|
117
|
+
const after = new Set(now.map(key));
|
|
118
|
+
const added = now.filter((a) => !before.has(key(a)));
|
|
119
|
+
const removed = marks.filter((a) => !after.has(key(a)));
|
|
120
|
+
if (added.length > 0 || removed.length > 0) {
|
|
121
|
+
push(t, 'marks', [...added.map((a) => `+ ${shapeOf(a)}`), ...removed.map((a) => `− ${shapeOf(a)}`)].join('; '), {
|
|
122
|
+
marks: now.map((a) => a.shape),
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
marks = now;
|
|
126
|
+
}
|
|
127
|
+
if (e.type === 5 && e.data.tag === 'deictic.end') push(t, 'end', 'recording stopped');
|
|
128
|
+
if (e.type !== 3) continue;
|
|
129
|
+
const d = e.data;
|
|
130
|
+
if (d.source === 0) {
|
|
131
|
+
for (const a of d.adds ?? []) add(a.node, a.parentId);
|
|
132
|
+
for (const a of d.attributes ?? []) {
|
|
133
|
+
const node = nodes.get(a.id);
|
|
134
|
+
if (node) node.attributes = { ...node.attributes, ...a.attributes };
|
|
135
|
+
}
|
|
136
|
+
for (const x of d.texts ?? []) {
|
|
137
|
+
const node = nodes.get(x.id);
|
|
138
|
+
if (node) node.textContent = x.value;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (d.source === 2 && [2, 3, 4].includes(d.type)) {
|
|
142
|
+
flushScroll();
|
|
143
|
+
flushTyping();
|
|
144
|
+
const what = { 2: 'click', 3: 'right-click', 4: 'double-click' }[d.type];
|
|
145
|
+
// A click a key made (Enter on a button) has no position.
|
|
146
|
+
const where = d.x === 0 && d.y === 0 ? ' by keyboard' : ` at (${Math.round(d.x)},${Math.round(d.y)}) in the viewport`;
|
|
147
|
+
push(t, what, `${describe(d.id)}${where}`, { node: d.id });
|
|
148
|
+
}
|
|
149
|
+
if (d.source === 3) {
|
|
150
|
+
if (scroll && scroll.id !== d.id) flushScroll();
|
|
151
|
+
scroll = { t: scroll?.t ?? t, id: d.id, x: Math.round(d.x), y: Math.round(d.y) };
|
|
152
|
+
}
|
|
153
|
+
if (d.source === 4) push(t, 'resize', `viewport ${d.width}×${d.height}`);
|
|
154
|
+
if (d.source === 5) {
|
|
155
|
+
if (typing && typing.id !== d.id) flushTyping();
|
|
156
|
+
typing = {
|
|
157
|
+
t: typing?.t ?? t,
|
|
158
|
+
id: d.id,
|
|
159
|
+
value: d.isChecked !== undefined && d.text === undefined ? String(d.isChecked) : JSON.stringify(d.text),
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
flushScroll();
|
|
164
|
+
flushTyping();
|
|
165
|
+
for (const c of kept.voice ?? []) push(c.at, 'voice', `clip ${c.id}, ${clock(c.duration)} long, until ${clock(c.at + c.duration)}`);
|
|
166
|
+
timeline.sort((a, b) => a.t - b.t);
|
|
167
|
+
|
|
168
|
+
const head = {
|
|
169
|
+
id,
|
|
170
|
+
page: kept.page,
|
|
171
|
+
viewport: kept.viewport,
|
|
172
|
+
colorScheme: kept.colorScheme ?? 'light',
|
|
173
|
+
startedAt: new Date(kept.startedAt ?? t0).toISOString(),
|
|
174
|
+
duration: kept.duration,
|
|
175
|
+
replay,
|
|
176
|
+
task: task?.id,
|
|
177
|
+
};
|
|
178
|
+
if (options.json) {
|
|
179
|
+
console.log(JSON.stringify({ ...head, timeline }, null, 2));
|
|
180
|
+
} else {
|
|
181
|
+
console.log(`Recording ${id}${task ? ` on task #${task.id}` : ''}: ${clock(kept.duration)} of ${kept.page}`);
|
|
182
|
+
console.log(`viewport ${kept.viewport.width}×${kept.viewport.height}, ${head.colorScheme}, started ${head.startedAt}`);
|
|
183
|
+
if (replay) console.log(`replays at ${replay} (add ?t=<seconds> to open it paused there)`);
|
|
184
|
+
console.log();
|
|
185
|
+
for (const e of timeline) console.log(`${e.at.padStart(6)} ${e.kind.padEnd(12)} ${e.text}`);
|
|
186
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// A task, briefly: what was asked, where (and whether that place has moved in the source since), the page,
|
|
3
|
+
// what's attached with the command to look at each, and the replies. Usage: task.mjs <id> [--out dir]
|
|
4
|
+
// --out downloads the attachments there.
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
6
|
+
import { dirname, join, resolve } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
|
|
9
|
+
import { deicticDirs, fail, parseArgs, vb } from './lib.mjs';
|
|
10
|
+
|
|
11
|
+
const { options, rest } = parseArgs(process.argv.slice(2));
|
|
12
|
+
if (rest[0] === undefined) fail('Name a task: task.mjs 68');
|
|
13
|
+
const { message: root, replies } = vb(['read', rest[0].replace(/^#/, '')], { json: true });
|
|
14
|
+
const [asked = '', where = ''] = root.text.split(/\n---\n/);
|
|
15
|
+
const at = root.labels['deictic.at'];
|
|
16
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
17
|
+
|
|
18
|
+
console.log(`#${root.id} ${root.task?.state ?? 'not a task'}, by ${root.author?.handle ?? root.by.actor}, ${root.createdAt}`);
|
|
19
|
+
console.log(`\nAsked:\n${asked.trim()}\n`);
|
|
20
|
+
// The part inside the element that was pointed at, where nothing marked it: what the person means.
|
|
21
|
+
const pointed = where.match(/\nPointed at, inside it: `([^`]*)`\n`{3,}\w*\n([\s\S]*?)\n`{3,}/);
|
|
22
|
+
// Where, from the labels: the place, the page, and the viewport to look at it in.
|
|
23
|
+
const facts = [
|
|
24
|
+
['deictic.project', (v) => `Project ${v}`],
|
|
25
|
+
['deictic.at', (v) => `${v} <${root.labels['deictic.tag'] ?? '?'}>`],
|
|
26
|
+
['deictic.url', (v) => v],
|
|
27
|
+
['deictic.viewport', (v) => `Viewport ${v}`],
|
|
28
|
+
['deictic.count', (v) => (v === '1' ? undefined : `${v} elements on the page come from that line`)],
|
|
29
|
+
['deictic.position', (v) => `In the screenshot at x,y ${v}, ${root.labels['deictic.size'] ?? '?'} (CSS pixels from its top left)`],
|
|
30
|
+
];
|
|
31
|
+
for (const [key, say] of facts) {
|
|
32
|
+
const line = root.labels[key] === undefined ? undefined : say(root.labels[key]);
|
|
33
|
+
if (line !== undefined) console.log(line);
|
|
34
|
+
}
|
|
35
|
+
// What no label holds: what's attached and drawn on it.
|
|
36
|
+
const told = (pointed ? where.slice(0, pointed.index) : where).trim();
|
|
37
|
+
if (told !== '') console.log(told);
|
|
38
|
+
if (pointed) console.log(`\nPointed at, inside it: ${pointed[1]}\n ${pointed[2]}`);
|
|
39
|
+
|
|
40
|
+
// The place as the task saw it, against the file now: the element's opening tag may have moved or changed.
|
|
41
|
+
if (at !== undefined) {
|
|
42
|
+
const [file, line] = [at.replace(/:\d+:\d+$/, ''), Number(at.split(':').at(-2))];
|
|
43
|
+
// Marks are from the dev server's root: here, above, or a folder with a .deictic/ of its own.
|
|
44
|
+
const roots = [process.cwd(), ...deicticDirs().map(dirname)];
|
|
45
|
+
const path = roots.map((r) => resolve(r, file)).find((p) => existsSync(p));
|
|
46
|
+
if (path === undefined) {
|
|
47
|
+
console.log(`\n${file} isn't under ${roots.join(' or ')}: find the dev server's root.`);
|
|
48
|
+
} else {
|
|
49
|
+
const lines = readFileSync(path, 'utf8').split('\n');
|
|
50
|
+
const first = root.labels['deictic.line'];
|
|
51
|
+
const now = lines[line - 1]?.trim();
|
|
52
|
+
if (first === undefined || now?.startsWith(first.slice(0, 40))) {
|
|
53
|
+
console.log(`\nSource: ${path}:${line}, as the task saw it.`);
|
|
54
|
+
} else {
|
|
55
|
+
const moved = lines.findIndex((l) => l.trim().startsWith(first.slice(0, 40)));
|
|
56
|
+
console.log(
|
|
57
|
+
moved >= 0
|
|
58
|
+
? `\nSource: moved to ${path}:${moved + 1} (the task says line ${line}).`
|
|
59
|
+
: `\nSource: ${path}:${line} no longer reads as the task saw it; it was:\n ${first}`,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (root.attachments.length > 0) console.log('\nAttached:');
|
|
66
|
+
const out = options.out?.[0] && resolve(options.out[0]);
|
|
67
|
+
if (out) mkdirSync(out, { recursive: true });
|
|
68
|
+
for (const a of root.attachments) {
|
|
69
|
+
const kb = `${Math.round(a.size / 1024)} KB`;
|
|
70
|
+
if (out) vb(['download', a.id, join(out, a.name)]);
|
|
71
|
+
const saved = out ? ` → ${join(out, a.name)}` : '';
|
|
72
|
+
if (a.name.startsWith('recording-')) {
|
|
73
|
+
console.log(` ${a.name} (${kb})${saved}`);
|
|
74
|
+
console.log(` timeline: node ${join(here, 'recording.mjs')} ${root.id}`);
|
|
75
|
+
console.log(` frames: node ${join(here, 'frame.mjs')} ${root.id}`);
|
|
76
|
+
} else if (a.name.startsWith('voice-')) {
|
|
77
|
+
console.log(` ${a.name} (${kb}), a voice clip${saved}`);
|
|
78
|
+
console.log(` speech: node ${join(here, 'voice.mjs')} ${root.id}`);
|
|
79
|
+
} else {
|
|
80
|
+
console.log(` ${a.name} (${a.type}, ${kb})${saved || `: vb download ${a.id} <dir>`}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (replies.length > 0) console.log('\nReplies:');
|
|
84
|
+
for (const r of replies) console.log(` ${r.author?.handle ?? r.by.actor}: ${r.text}`);
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// What was said in voice clips, with when: Whisper on this machine, through transformers.js. For a recording, the
|
|
3
|
+
// times are the recording's, to line up with its timeline. Nothing leaves the machine once the model is downloaded.
|
|
4
|
+
//
|
|
5
|
+
// Usage: transcribe.mjs <task | replay URL | recording ID | file | clip ID> [--model base] [--language en] [--json]
|
|
6
|
+
// transcribe.mjs --setup [--model base] installs it: ask the person first
|
|
7
|
+
//
|
|
8
|
+
// Setup puts @huggingface/transformers and the model in ~/.cache/deictic/transcribe (DEICTIC_CACHE moves it),
|
|
9
|
+
// outside the project. Models: tiny (~40 MB), base (~77 MB, the default), small (~250 MB), large-v3-turbo
|
|
10
|
+
// (~800 MB), or any ONNX Whisper on Hugging Face by its ID. Needs ffmpeg on the PATH.
|
|
11
|
+
import { spawnSync } from 'node:child_process';
|
|
12
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
13
|
+
import { createRequire } from 'node:module';
|
|
14
|
+
import { homedir } from 'node:os';
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
import { pathToFileURL } from 'node:url';
|
|
17
|
+
|
|
18
|
+
import { clock, fail, ffmpeg, parseArgs, voiceClips } from './lib.mjs';
|
|
19
|
+
|
|
20
|
+
// Pinned, so a setup installs what the script was written against; move it on deliberately.
|
|
21
|
+
const TRANSFORMERS = '@huggingface/transformers@4.3.2';
|
|
22
|
+
const MODELS = { tiny: 'whisper-tiny', base: 'whisper-base', small: 'whisper-small', 'large-v3-turbo': 'whisper-large-v3-turbo' };
|
|
23
|
+
|
|
24
|
+
const { options, rest } = parseArgs(process.argv.slice(2), ['setup', 'json']);
|
|
25
|
+
const size = options.model?.[0] ?? 'base';
|
|
26
|
+
const model = size.includes('/')
|
|
27
|
+
? size
|
|
28
|
+
: `onnx-community/${MODELS[size] ?? fail(`--model is one of ${Object.keys(MODELS).join(', ')}, or a model ID`)}`;
|
|
29
|
+
const dir = join(process.env.DEICTIC_CACHE ?? join(homedir(), '.cache', 'deictic'), 'transcribe');
|
|
30
|
+
const models = join(dir, 'models');
|
|
31
|
+
const installed = existsSync(join(dir, 'node_modules', '@huggingface', 'transformers', 'package.json'));
|
|
32
|
+
const downloaded = existsSync(join(models, ...model.split('/')));
|
|
33
|
+
|
|
34
|
+
if (options.setup) {
|
|
35
|
+
mkdirSync(dir, { recursive: true });
|
|
36
|
+
if (!existsSync(join(dir, 'package.json'))) writeFileSync(join(dir, 'package.json'), '{ "private": true }\n');
|
|
37
|
+
if (!installed) {
|
|
38
|
+
console.log(`Installing ${TRANSFORMERS} in ${dir}…`);
|
|
39
|
+
const windows = process.platform === 'win32';
|
|
40
|
+
const args = ['install', '--prefix', dir, '--no-audit', '--no-fund', '--save-exact', TRANSFORMERS];
|
|
41
|
+
const run = spawnSync(windows ? `npm ${args.map((a) => `"${a}"`).join(' ')}` : 'npm', windows ? [] : args, {
|
|
42
|
+
stdio: 'inherit',
|
|
43
|
+
shell: windows,
|
|
44
|
+
});
|
|
45
|
+
if (run.status !== 0) fail(`npm install failed (${run.error?.message ?? `exit ${run.status}`}).`);
|
|
46
|
+
}
|
|
47
|
+
} else if (!installed || !downloaded) {
|
|
48
|
+
fail(
|
|
49
|
+
`Local transcription isn't set up${installed ? ` with the ${size} model` : ''}. Ask the person first: it downloads ` +
|
|
50
|
+
`${installed ? '' : `${TRANSFORMERS} (with ONNX Runtime, ~470 MB) and `}Whisper ${size} into ${dir}, outside ` +
|
|
51
|
+
`the project; after that, audio is transcribed on this machine. On yes: node ${process.argv[1]} --setup` +
|
|
52
|
+
(size === 'base' ? '' : ` --model ${size}`),
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const transformers = await import(pathToFileURL(createRequire(join(dir, 'package.json')).resolve('@huggingface/transformers')).href);
|
|
57
|
+
transformers.env.cacheDir = models;
|
|
58
|
+
// Only setup downloads; a transcription uses what's here.
|
|
59
|
+
transformers.env.allowRemoteModels = Boolean(options.setup);
|
|
60
|
+
if (options.setup) console.log(`Downloading ${model} (quantized) into ${models}…`);
|
|
61
|
+
const asr = await transformers.pipeline('automatic-speech-recognition', model, { dtype: 'q8' });
|
|
62
|
+
if (options.setup) {
|
|
63
|
+
console.log(`Ready: node ${process.argv[1]} <task>${size === 'base' ? '' : ` --model ${size}`}`);
|
|
64
|
+
if (rest[0] === undefined) process.exit(0);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const results = [];
|
|
68
|
+
for (const c of await voiceClips(rest[0])) {
|
|
69
|
+
// Whisper takes 16 kHz mono samples; ffmpeg decodes the clip (webm, ogg or mp4) to them.
|
|
70
|
+
const raw = ffmpeg(['-loglevel', 'error', '-i', c.file, '-f', 'f32le', '-ac', '1', '-ar', '16000', '-'], 'buffer').stdout;
|
|
71
|
+
const audio = new Float32Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength - (raw.byteLength % 4)));
|
|
72
|
+
const out = await asr(audio, {
|
|
73
|
+
return_timestamps: true,
|
|
74
|
+
chunk_length_s: 30,
|
|
75
|
+
stride_length_s: 5,
|
|
76
|
+
...(options.language ? { language: options.language[0] } : {}),
|
|
77
|
+
});
|
|
78
|
+
const said = (out.chunks ?? [{ timestamp: [0, audio.length / 16000], text: out.text }]).map(({ timestamp: [from, to], text }) => ({
|
|
79
|
+
from: c.at + from * 1000,
|
|
80
|
+
to: c.at + (to ?? audio.length / 16000) * 1000,
|
|
81
|
+
text: text.trim(),
|
|
82
|
+
}));
|
|
83
|
+
results.push({ ...c, text: out.text.trim(), said });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (options.json) {
|
|
87
|
+
console.log(JSON.stringify(results, null, 2));
|
|
88
|
+
} else {
|
|
89
|
+
for (const r of results) {
|
|
90
|
+
console.log(`clip ${r.id} (${r.recording ? `in recording ${r.recording}, from ${clock(r.at)}` : 'a voice note'}):`);
|
|
91
|
+
for (const s of r.said) console.log(` ${clock(s.from).padStart(6)} – ${clock(s.to).padStart(6)} ${s.text}`);
|
|
92
|
+
}
|
|
93
|
+
}
|