@hackbuild/speak 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/text.js ADDED
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Text for a voice: what to say and where each spoken character came
3
+ * from. Offsets are kept in the caller's text (the visible reply, with
4
+ * action tags already removed), so lip sync and action cues share one
5
+ * coordinate space with the tag parser in @hackbuild/structured.
6
+ */
7
+ // pictographs plus skin tone modifiers, variation selectors, the zero width joiner and the keycap mark, by code point
8
+ const cp = (n) => `\\u{${n.toString(16)}}`;
9
+ const PICTO = new RegExp(`[\\p{Extended_Pictographic}${cp(0x1f3fb)}-${cp(0x1f3ff)}${cp(0xfe0e)}${cp(0xfe0f)}${cp(0x200d)}${cp(0x20e3)}]+`, "gu");
10
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
11
+ /**
12
+ * Strip what should not be read aloud: think blocks (closed or still
13
+ * open), code fences, markdown marks, link targets, emoji and variation
14
+ * selectors; read bare URLs as one word; apply the lexicon; collapse
15
+ * whitespace. Returns the text and an offset map back into the input.
16
+ */
17
+ export function speakable(input, o = {}) {
18
+ const edits = [];
19
+ const claimed = [];
20
+ const free = (a, b) => claimed.every(([x, y]) => b <= x || a >= y);
21
+ const add = (start, end, repl) => {
22
+ if (end <= start || !free(start, end))
23
+ return;
24
+ claimed.push([start, end]);
25
+ edits.push({ start, end, repl });
26
+ };
27
+ const each = (re, fn) => {
28
+ for (const m of input.matchAll(re))
29
+ fn(m);
30
+ };
31
+ each(/<(think|thinking|thought)>[\s\S]*?(<\/\1>|$)/gi, (m) => add(m.index, m.index + m[0].length, " "));
32
+ each(/```[\s\S]*?(```|$)/g, (m) => add(m.index, m.index + m[0].length, " "));
33
+ each(/\[([^\]\n]+)\]\((\S+?)\)/g, (m) => {
34
+ add(m.index, m.index + 1, "");
35
+ add(m.index + 1 + m[1].length, m.index + m[0].length, "");
36
+ });
37
+ each(/\bhttps?:\/\/\S+|\bwww\.\S+\.\S+/g, (m) => {
38
+ const t = m[0].replace(/[.,;:?)]+$/, "");
39
+ add(m.index, m.index + t.length, o.url ?? "link");
40
+ });
41
+ for (const [k, v] of Object.entries(o.lexicon ?? {})) {
42
+ each(new RegExp(`(?<![\\p{L}\\p{N}])${esc(k)}(?![\\p{L}\\p{N}])`, "gu"), (m) => add(m.index, m.index + m[0].length, v));
43
+ }
44
+ each(/^[ \t]*(#{1,6}|>|[-*+]|\d+[.)])[ \t]+/gm, (m) => add(m.index, m.index + m[0].length, ""));
45
+ each(/[*_~`]+/g, (m) => add(m.index, m.index + m[0].length, ""));
46
+ each(PICTO, (m) => add(m.index, m.index + m[0].length, " "));
47
+ edits.sort((a, b) => a.start - b.start);
48
+ let text = "";
49
+ const map = [];
50
+ const push = (ch, at) => {
51
+ if (/\s/.test(ch)) {
52
+ if (!text.length || /\s$/.test(text))
53
+ return;
54
+ ch = " ";
55
+ }
56
+ text += ch;
57
+ map.push(at);
58
+ };
59
+ let i = 0;
60
+ for (const e of edits) {
61
+ for (; i < e.start; i++)
62
+ push(input[i], i);
63
+ for (const ch of e.repl)
64
+ push(ch, e.start);
65
+ i = e.end;
66
+ }
67
+ for (; i < input.length; i++)
68
+ push(input[i], i);
69
+ while (text.endsWith(" ")) {
70
+ text = text.slice(0, -1);
71
+ map.pop();
72
+ }
73
+ map.push(input.length);
74
+ return { text, map: Int32Array.from(map) };
75
+ }
76
+ const ABBREV = /(?:\b(?:mr|mrs|ms|dr|st|vs|etc|e\.g|i\.e|no|approx))\.$/i;
77
+ /**
78
+ * Cuts a growing reply into segments for a voice. The first segment ends
79
+ * at a clause once it is 24 characters long so speech starts early; later
80
+ * segments end at sentences, or at the last clause or space before 160
81
+ * characters. `take(full, final)` returns the segments completed since the
82
+ * last call.
83
+ */
84
+ export class SegmentCutter {
85
+ pos = 0;
86
+ n = 0;
87
+ first;
88
+ max;
89
+ constructor(o = {}) {
90
+ this.first = o.firstClause ?? 24;
91
+ this.max = o.maxChars ?? 160;
92
+ }
93
+ reset() {
94
+ this.pos = 0;
95
+ this.n = 0;
96
+ }
97
+ take(full, final) {
98
+ const out = [];
99
+ for (;;) {
100
+ const cut = this.findCut(full, final);
101
+ if (cut < 0)
102
+ break;
103
+ const raw = full.slice(this.pos, cut);
104
+ const lead = raw.length - raw.trimStart().length;
105
+ const t = raw.trim();
106
+ if (t)
107
+ out.push({ index: this.n++, text: t, start: this.pos + lead, end: this.pos + lead + t.length });
108
+ this.pos = cut;
109
+ }
110
+ return out;
111
+ }
112
+ findCut(full, final) {
113
+ const rest = full.slice(this.pos);
114
+ if (!rest.trim())
115
+ return final && rest.length ? full.length : -1;
116
+ const sentence = /[.?!]+["')\]]*(\s|$)|\n/g;
117
+ let m;
118
+ let sent = -1;
119
+ while ((m = sentence.exec(rest))) {
120
+ const endsAt = m.index + m[0].length;
121
+ if (m[1] === "" && !final && endsAt === rest.length)
122
+ break; // the stream may continue the word
123
+ if (m[0] !== "\n" && ABBREV.test(rest.slice(0, m.index + 1)))
124
+ continue;
125
+ if (rest.slice(0, m.index).trim().length === 0)
126
+ continue;
127
+ sent = endsAt;
128
+ break;
129
+ }
130
+ if (this.n === 0) {
131
+ const c = /[,;:]\s/g;
132
+ while ((m = c.exec(rest))) {
133
+ if (sent >= 0 && m.index >= sent)
134
+ break;
135
+ if (m.index >= this.first - 1)
136
+ return this.pos + m.index + 1;
137
+ }
138
+ }
139
+ if (sent >= 0)
140
+ return this.pos + sent;
141
+ if (rest.length > this.max) {
142
+ const head = rest.slice(0, this.max);
143
+ const clause = Math.max(head.lastIndexOf(", "), head.lastIndexOf("; "), head.lastIndexOf(": "));
144
+ const at = clause > 0 ? clause + 1 : head.lastIndexOf(" ");
145
+ return this.pos + (at > 0 ? at : this.max);
146
+ }
147
+ return final ? full.length : -1;
148
+ }
149
+ }
150
+ /** Word spans in a text: [start, end) character offsets. */
151
+ export function wordSpans(text) {
152
+ return [...text.matchAll(/[\p{L}\p{N}'’]+/gu)].map((m) => ({ start: m.index, end: m.index + m[0].length }));
153
+ }
154
+ /**
155
+ * Estimated word times for an engine that gives none: each word gets a
156
+ * share of the duration by its character count plus one for the gap.
157
+ * Marked estimated wherever it is reported.
158
+ */
159
+ export function estimateWordTimes(text, duration) {
160
+ const w = wordSpans(text);
161
+ const weight = w.map((x) => x.end - x.start + 1);
162
+ const total = weight.reduce((a, b) => a + b, 0) || 1;
163
+ let t = 0;
164
+ return w.map((x, i) => {
165
+ const d = (weight[i] / total) * duration;
166
+ const r = { ...x, t0: t, t1: t + d };
167
+ t += d;
168
+ return r;
169
+ });
170
+ }
@@ -0,0 +1,64 @@
1
+ /** Engine contracts. A PCM engine yields audio for the shared player; a native engine plays itself. */
2
+ export interface VoiceConfig {
3
+ voice?: string;
4
+ /** 1 is the engine's normal speed. */
5
+ rate?: number;
6
+ pitch?: number;
7
+ }
8
+ /** A word or phoneme with its span in the text the engine was given and its time from the start of that text's audio, in seconds. */
9
+ export interface Timed {
10
+ start: number;
11
+ end: number;
12
+ t0: number;
13
+ t1: number;
14
+ /** A phoneme symbol when the engine reports phonemes. */
15
+ phoneme?: string;
16
+ }
17
+ export interface PcmChunk {
18
+ samples: Float32Array;
19
+ sampleRate: number;
20
+ /** Timings inside this chunk, times relative to the chunk start. */
21
+ words?: Timed[];
22
+ phonemes?: Timed[];
23
+ }
24
+ export interface EngineStatus {
25
+ engine: string;
26
+ kind: "loading" | "ready" | "failed" | "patch-missed" | "watchdog" | "licence";
27
+ text: string;
28
+ progress?: number;
29
+ }
30
+ export interface LoadContext {
31
+ signal?: AbortSignal;
32
+ onStatus?: (s: EngineStatus) => void;
33
+ }
34
+ export interface PcmEngine {
35
+ readonly kind: "pcm";
36
+ readonly id: string;
37
+ /** Weight licence, stated on first load. */
38
+ readonly licence: string;
39
+ /** Renders to a buffer for "save wav". PCM engines can unless this is false. */
40
+ readonly offline?: boolean;
41
+ load(ctx: LoadContext): Promise<void>;
42
+ synth(text: string, cfg: VoiceConfig, signal: AbortSignal): AsyncIterable<PcmChunk>;
43
+ voices?(): string[];
44
+ dispose?(): void;
45
+ }
46
+ export interface NativeEngine {
47
+ readonly kind: "native";
48
+ readonly id: string;
49
+ readonly licence: string;
50
+ /** Always false: a native engine plays through the platform and hands back no samples. */
51
+ readonly offline?: false;
52
+ load(ctx: LoadContext): Promise<void>;
53
+ /**
54
+ * Speak and resolve when done. onBoundary gets character offsets in `text`;
55
+ * onStart fires when the platform says audio started, when it says so.
56
+ */
57
+ speak(text: string, cfg: VoiceConfig, hooks: {
58
+ onBoundary(charIndex: number, charLength?: number): void;
59
+ onStart?(): void;
60
+ }, signal: AbortSignal): Promise<void>;
61
+ stop(): void;
62
+ voices?(): string[];
63
+ }
64
+ export type Engine = PcmEngine | NativeEngine;
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ /** Engine contracts. A PCM engine yields audio for the shared player; a native engine plays itself. */
2
+ export {};
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@hackbuild/speak",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Speech out in a tab: an engine chain over Kokoro, Pocket TTS and Web Speech, first clause streaming, gapless playback with one analyser, a watchdog, and text offsets for lip sync and action cues.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Moheeb Zara <hackbuildvideo@gmail.com>",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/hackbuild/hackbuild-browser-ai.git",
11
+ "directory": "packages/speak"
12
+ },
13
+ "engines": {
14
+ "node": "^22.18.0 || >=24.11.0"
15
+ },
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "README.md",
26
+ "LICENSE"
27
+ ],
28
+ "unpkg": "./dist/single/index.iife.js",
29
+ "jsdelivr": "./dist/single/index.iife.js",
30
+ "scripts": {
31
+ "build": "tsc -b"
32
+ },
33
+ "dependencies": {
34
+ "@hackbuild/ai-env": "0.1.0",
35
+ "@hackbuild/models": "0.1.0",
36
+ "@hackbuild/audio-dsp": "0.1.0"
37
+ },
38
+ "peerDependencies": {
39
+ "bellows-voice": "0.8.0",
40
+ "bellowsjs": "0.5.0"
41
+ },
42
+ "peerDependenciesMeta": {
43
+ "bellows-voice": {
44
+ "optional": true
45
+ },
46
+ "bellowsjs": {
47
+ "optional": true
48
+ }
49
+ }
50
+ }