@beff/aula-cli 0.0.1 → 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.
Files changed (38) hide show
  1. package/README.md +11 -1
  2. package/dist/licenses/aula-g2p-NOTICE.txt +13 -0
  3. package/dist/licenses/espeak-ng-COPYING.txt +674 -0
  4. package/dist/licenses/fonts-OFL-JetBrainsMono.txt +93 -0
  5. package/dist/licenses/fonts-OFL-NunitoSans.txt +93 -0
  6. package/dist/src/aula-render.core.wasm +0 -0
  7. package/dist/src/aula-voice-tts-ZXQ7XXHJ.js +14 -0
  8. package/dist/src/chunk-2XGNOG2U.js +28 -0
  9. package/dist/src/chunk-46KT47TH.js +21 -0
  10. package/dist/src/chunk-7KT36JRP.js +1282 -0
  11. package/dist/src/chunk-GFCJYE75.js +42 -0
  12. package/dist/src/chunk-IAQZ6DTC.js +271 -0
  13. package/dist/src/chunk-QWNBVWUQ.js +1105 -0
  14. package/dist/src/chunk-XUBCUJW5.js +104 -0
  15. package/dist/src/chunk-YX73KJQ6.js +577 -0
  16. package/dist/src/cli.js +334 -0
  17. package/dist/src/commands-M246OWYJ.js +27 -0
  18. package/dist/src/problems-Y67BY7WB.js +12 -0
  19. package/dist/src/project-NWT5MDQI.js +11 -0
  20. package/dist/src/render-child.js +3771 -0
  21. package/dist/src/run-CTVGU7EK.js +127 -0
  22. package/dist/src/server-5OGXX6BF.js +220 -0
  23. package/dist/web/app/assets/__vite-browser-external-BN30sEqc.js +1 -0
  24. package/dist/web/app/assets/__vite-browser-external-BtQTJ51O.js +1 -0
  25. package/dist/web/app/assets/aula-method.js +1 -0
  26. package/dist/web/app/assets/aula-voice-worker-DymX5vwM.js +52 -0
  27. package/dist/web/app/assets/aula.core-BtiPQSZi.wasm +0 -0
  28. package/dist/web/app/assets/aula.core5-YhDIb7Me.wasm +0 -0
  29. package/dist/web/app/assets/aula.js +1 -0
  30. package/dist/web/app/assets/build-worker.js +696 -0
  31. package/dist/web/app/assets/esbuild-BaXVPFT2.wasm +0 -0
  32. package/dist/web/app/assets/index-B8_aMtuI.js +53 -0
  33. package/dist/web/app/assets/index-cL-Dm_aw.css +2 -0
  34. package/dist/web/app/assets/protocol-CnlzsyRt.js +15 -0
  35. package/dist/web/app/assets/rolldown-runtime-BLXQ4ufn.js +1 -0
  36. package/dist/web/app/assets/src-CmWmmzpF.js +25 -0
  37. package/dist/web/app/index.html +15 -0
  38. package/package.json +27 -5
@@ -0,0 +1,104 @@
1
+ // ../aula-narration/src/script.ts
2
+ import { chapterNarration } from "@beff/aula/text";
3
+ function joinChapter(cues, speeches) {
4
+ let rate = 0;
5
+ for (const [i, speech] of speeches.entries()) {
6
+ if (!speech.samples.length || speech.samples.some((s) => !Number.isFinite(s))) {
7
+ const text = cues[i]?.text.slice(0, 60) ?? "";
8
+ throw new Error(`the narrator returned empty or invalid audio for ${JSON.stringify(text)}`);
9
+ }
10
+ if (rate !== 0 && speech.sampleRate !== rate) throw new Error("the narrator changed its sample rate");
11
+ rate = speech.sampleRate;
12
+ }
13
+ const spoken = speeches.map((s) => ({
14
+ samples: s.samples.length,
15
+ words: s.words.map((w) => ({ text: w.text, char: w.char, start: w.start }))
16
+ }));
17
+ const narration = chapterNarration(cues, spoken, rate);
18
+ const samples = new Float32Array(narration.endFrame);
19
+ for (const [i, speech] of speeches.entries()) samples.set(speech.samples, narration.cues[i]?.speechStartFrame ?? 0);
20
+ return { samples, narration };
21
+ }
22
+ function withWaits(samples, waits) {
23
+ if (waits.length === 0) return samples;
24
+ const out = new Float32Array(samples.length + waits.reduce((sum, w) => sum + w.samples, 0));
25
+ let from = 0;
26
+ let to = 0;
27
+ for (const wait of waits.toSorted((a, b) => a.sample - b.sample)) {
28
+ const at = Math.min(wait.sample, samples.length);
29
+ out.set(samples.subarray(from, at), to);
30
+ to += at - from + wait.samples;
31
+ from = at;
32
+ }
33
+ out.set(samples.subarray(from), to);
34
+ return out;
35
+ }
36
+ function timeChapter(cues, timings) {
37
+ const rate = timings[0]?.sampleRate ?? 0;
38
+ if (timings.some((t) => t.sampleRate !== rate)) throw new Error("the narrator changed its sample rate");
39
+ const spoken = timings.map((t) => ({
40
+ samples: t.samples,
41
+ words: t.words.map((w) => ({ text: w.text, char: w.char, start: w.start }))
42
+ }));
43
+ return chapterNarration(cues, spoken, rate);
44
+ }
45
+ async function narrateScript(speak, chapters, speaking) {
46
+ const count = chapters.reduce((sum, c) => sum + c.length, 0);
47
+ let spoken = 0;
48
+ const narrated = [];
49
+ for (const cues of chapters) {
50
+ const speeches = [];
51
+ for (const cue of cues) {
52
+ spoken += 1;
53
+ speaking(spoken, count, cue);
54
+ speeches.push(await speak(cue.text, cue.speed));
55
+ }
56
+ narrated.push(joinChapter(cues, speeches));
57
+ }
58
+ if (!narrated.some((c) => c.narration.sampleRate > 0)) throw new Error("the script has no cues");
59
+ return narrated;
60
+ }
61
+ function scriptAudio(chapters, waits) {
62
+ const sounds = chapters.map((c, i) => withWaits(c.samples, waits[i] ?? []));
63
+ const samples = new Float32Array(sounds.reduce((sum, s) => sum + s.length, 0));
64
+ let at = 0;
65
+ for (const sound of sounds) {
66
+ samples.set(sound, at);
67
+ at += sound.length;
68
+ }
69
+ const sampleRate = chapters.find((c) => c.narration.sampleRate > 0)?.narration.sampleRate ?? 0;
70
+ return { samples, sampleRate };
71
+ }
72
+
73
+ // ../aula-narration/src/wav.ts
74
+ function wav(samples, rate) {
75
+ const bytes = new Uint8Array(44 + samples.length * 2);
76
+ const view = new DataView(bytes.buffer);
77
+ const text = (at, value) => {
78
+ for (let i = 0; i < value.length; i++) view.setUint8(at + i, value.charCodeAt(i));
79
+ };
80
+ text(0, "RIFF");
81
+ view.setUint32(4, 36 + samples.length * 2, true);
82
+ text(8, "WAVE");
83
+ text(12, "fmt ");
84
+ view.setUint32(16, 16, true);
85
+ view.setUint16(20, 1, true);
86
+ view.setUint16(22, 1, true);
87
+ view.setUint32(24, rate, true);
88
+ view.setUint32(28, rate * 2, true);
89
+ view.setUint16(32, 2, true);
90
+ view.setUint16(34, 16, true);
91
+ text(36, "data");
92
+ view.setUint32(40, samples.length * 2, true);
93
+ samples.forEach((sample, i) => {
94
+ view.setInt16(44 + i * 2, Math.round(Math.min(1, Math.max(-1, sample)) * 32767), true);
95
+ });
96
+ return bytes;
97
+ }
98
+
99
+ export {
100
+ timeChapter,
101
+ narrateScript,
102
+ scriptAudio,
103
+ wav
104
+ };
@@ -0,0 +1,577 @@
1
+ // ../aula-narration/src/align.ts
2
+ function tokens(text) {
3
+ return [...text.matchAll(/\S+/g)].map((match) => ({ text: match[0], char: match.index }));
4
+ }
5
+ function roundHalfEven(value) {
6
+ const floor = Math.floor(value);
7
+ const rest = value - floor;
8
+ if (rest > 0.5) return floor + 1;
9
+ if (rest < 0.5) return floor;
10
+ return floor % 2 === 0 ? floor : floor + 1;
11
+ }
12
+ var ms = (seconds) => roundHalfEven(seconds * 1e3) / 1e3;
13
+ function alignWords(text, spoken, read) {
14
+ const source = tokens(text);
15
+ if (read.length !== source.length) {
16
+ throw new Error(`${String(source.length)} words but ${String(read.length)} readings`);
17
+ }
18
+ const phones = [];
19
+ const owner = [];
20
+ read.forEach((word2, index) => {
21
+ for (const phone of word2) {
22
+ phones.push(phone);
23
+ owner.push(index);
24
+ }
25
+ });
26
+ const n = phones.length;
27
+ const m = spoken.length;
28
+ const width = m + 1;
29
+ const cost = new Uint32Array((n + 1) * width);
30
+ const at = (i2, j2) => cost[i2 * width + j2] ?? 0;
31
+ const differ = (i2, j2) => phones[i2 - 1] === spoken[j2 - 1]?.phoneme ? 0 : 1;
32
+ for (let i2 = 0; i2 <= n; i2++) cost[i2 * width] = i2;
33
+ for (let j2 = 0; j2 <= m; j2++) cost[j2] = j2;
34
+ for (let i2 = 1; i2 <= n; i2++) {
35
+ for (let j2 = 1; j2 <= m; j2++) {
36
+ cost[i2 * width + j2] = Math.min(at(i2 - 1, j2 - 1) + differ(i2, j2), at(i2 - 1, j2) + 1, at(i2, j2 - 1) + 1);
37
+ }
38
+ }
39
+ const word = new Int32Array(m).fill(-1);
40
+ let i = n;
41
+ let j = m;
42
+ while (j > 0) {
43
+ const here = at(i, j);
44
+ if (i > 0 && here === at(i - 1, j - 1) + differ(i, j)) {
45
+ word[j - 1] = owner[i - 1] ?? 0;
46
+ i--;
47
+ j--;
48
+ } else if (i > 0 && here === at(i - 1, j) + 1) i--;
49
+ else {
50
+ word[j - 1] = owner[Math.max(i - 1, 0)] ?? 0;
51
+ j--;
52
+ }
53
+ }
54
+ const starts = new Float64Array(source.length).fill(Number.NaN);
55
+ const ends = new Float64Array(source.length).fill(Number.NaN);
56
+ spoken.forEach((phone, k) => {
57
+ const w = word[k] ?? -1;
58
+ if (w < 0) return;
59
+ if (Number.isNaN(starts[w] ?? Number.NaN)) starts[w] = phone.start;
60
+ ends[w] = phone.end;
61
+ });
62
+ let last = 0;
63
+ return source.map((token, w) => {
64
+ const start = starts[w] ?? Number.NaN;
65
+ const end = ends[w] ?? Number.NaN;
66
+ const found = !Number.isNaN(start) && start >= last;
67
+ const time = { text: token.text, char: token.char, start: ms(found ? start : last), end: ms(found ? end : last) };
68
+ if (found) last = end;
69
+ return time;
70
+ });
71
+ }
72
+
73
+ // ../aula-narration/src/tokens.ts
74
+ var MAX_PHONEME_LENGTH = 510;
75
+ var SENTENCE_MARKS = ".!?\u2026";
76
+ var CLAUSE_MARKS = ",;:";
77
+ var SENTENCE_PAUSE = 0.25;
78
+ var CLAUSE_PAUSE = 0.1;
79
+ var escape = (marks) => marks.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
80
+ var BOUNDARIES = [
81
+ new RegExp(`(?<=[${escape(SENTENCE_MARKS)}])\\s+`),
82
+ new RegExp(`(?<=[${escape(CLAUSE_MARKS)}])\\s+`),
83
+ /\s+/
84
+ ];
85
+ function* atoms(phonemes, maxLength, level = 0) {
86
+ if (phonemes.length <= maxLength) {
87
+ if (phonemes) yield phonemes;
88
+ return;
89
+ }
90
+ for (let index = level; index < BOUNDARIES.length; index++) {
91
+ const boundary = BOUNDARIES[index];
92
+ const pieces = boundary ? phonemes.split(boundary) : [];
93
+ if (pieces.length > 1) {
94
+ for (const piece of pieces) yield* atoms(piece.trim(), maxLength, index + 1);
95
+ return;
96
+ }
97
+ }
98
+ for (let start = 0; start < phonemes.length; start += maxLength) yield phonemes.slice(start, start + maxLength);
99
+ }
100
+ function pack(lengths, limit) {
101
+ const batches = [];
102
+ let start = 0;
103
+ let size = 0;
104
+ lengths.forEach((length, index) => {
105
+ const candidate = index === start ? length : size + 1 + length;
106
+ if (candidate > limit && index > start) {
107
+ batches.push([start, index]);
108
+ start = index;
109
+ size = length;
110
+ } else size = candidate;
111
+ });
112
+ if (lengths.length) batches.push([start, lengths.length]);
113
+ return batches;
114
+ }
115
+ function splitPhonemes(phonemes, maxLength = MAX_PHONEME_LENGTH) {
116
+ const all = [...atoms(phonemes.trim(), maxLength)];
117
+ if (!all.length) return [];
118
+ const lengths = all.map((atom) => atom.length);
119
+ const fewest = pack(lengths, maxLength).length;
120
+ let low = Math.max(...lengths);
121
+ let high = maxLength;
122
+ while (low < high) {
123
+ const middle = Math.floor((low + high) / 2);
124
+ if (pack(lengths, middle).length <= fewest) high = middle;
125
+ else low = middle + 1;
126
+ }
127
+ return pack(lengths, low).map(([start, end]) => all.slice(start, end).join(" "));
128
+ }
129
+ function pauseAfter(phonemes) {
130
+ return markPause(phonemes.trimEnd().slice(-1));
131
+ }
132
+ function markPause(phoneme) {
133
+ if (phoneme && SENTENCE_MARKS.includes(phoneme)) return SENTENCE_PAUSE;
134
+ if (phoneme && CLAUSE_MARKS.includes(phoneme)) return CLAUSE_PAUSE;
135
+ return 0;
136
+ }
137
+ function tokenize(vocab, phonemes) {
138
+ const ids = [];
139
+ const known = [];
140
+ for (const phoneme of phonemes) {
141
+ const id = vocab.get(phoneme);
142
+ if (id === void 0) continue;
143
+ ids.push(id);
144
+ known.push(phoneme);
145
+ }
146
+ return { ids, known };
147
+ }
148
+ async function batchesOf(phonemize2, text, maxLength = MAX_PHONEME_LENGTH) {
149
+ const phonemes = (await phonemize2(text)).split(/\s+/).filter(Boolean).join(" ");
150
+ return splitPhonemes(phonemes, maxLength);
151
+ }
152
+ async function tokenBatches(vocab, phonemize2, text) {
153
+ return (await batchesOf(phonemize2, text)).map((phonemes) => ({ phonemes, ids: tokenize(vocab, phonemes).ids }));
154
+ }
155
+ var STRESS = "\u02C8\u02CC";
156
+ var isSound = (phoneme) => new RegExp("\\p{L}", "u").test(phoneme) && !STRESS.includes(phoneme);
157
+ async function timesOfWords(phonemize2, text, timings) {
158
+ const spoken = timings.filter((timing) => isSound(timing.phoneme));
159
+ if (!spoken.length) throw new Error("the model gave no phoneme timings");
160
+ const read = [];
161
+ for (const word of tokens(text)) read.push(Array.from(await phonemize2(word.text)).filter(isSound));
162
+ return alignWords(text, spoken, read);
163
+ }
164
+
165
+ // ../aula-narration/src/vocab.ts
166
+ var KOKORO_VOCAB = /* @__PURE__ */ new Map([
167
+ ["$", 0],
168
+ [";", 1],
169
+ [":", 2],
170
+ [",", 3],
171
+ [".", 4],
172
+ ["!", 5],
173
+ ["?", 6],
174
+ ["\u2014", 9],
175
+ ["\u2026", 10],
176
+ ['"', 11],
177
+ ["(", 12],
178
+ [")", 13],
179
+ ["\u201C", 14],
180
+ ["\u201D", 15],
181
+ [" ", 16],
182
+ ["\u0303", 17],
183
+ ["\u02A3", 18],
184
+ ["\u02A5", 19],
185
+ ["\u02A6", 20],
186
+ ["\u02A8", 21],
187
+ ["\u1D5D", 22],
188
+ ["\uAB67", 23],
189
+ ["A", 24],
190
+ ["I", 25],
191
+ ["O", 31],
192
+ ["Q", 33],
193
+ ["S", 35],
194
+ ["T", 36],
195
+ ["W", 39],
196
+ ["Y", 41],
197
+ ["\u1D4A", 42],
198
+ ["a", 43],
199
+ ["b", 44],
200
+ ["c", 45],
201
+ ["d", 46],
202
+ ["e", 47],
203
+ ["f", 48],
204
+ ["h", 50],
205
+ ["i", 51],
206
+ ["j", 52],
207
+ ["k", 53],
208
+ ["l", 54],
209
+ ["m", 55],
210
+ ["n", 56],
211
+ ["o", 57],
212
+ ["p", 58],
213
+ ["q", 59],
214
+ ["r", 60],
215
+ ["s", 61],
216
+ ["t", 62],
217
+ ["u", 63],
218
+ ["v", 64],
219
+ ["w", 65],
220
+ ["x", 66],
221
+ ["y", 67],
222
+ ["z", 68],
223
+ ["\u0251", 69],
224
+ ["\u0250", 70],
225
+ ["\u0252", 71],
226
+ ["\xE6", 72],
227
+ ["\u03B2", 75],
228
+ ["\u0254", 76],
229
+ ["\u0255", 77],
230
+ ["\xE7", 78],
231
+ ["\u0256", 80],
232
+ ["\xF0", 81],
233
+ ["\u02A4", 82],
234
+ ["\u0259", 83],
235
+ ["\u025A", 85],
236
+ ["\u025B", 86],
237
+ ["\u025C", 87],
238
+ ["\u025F", 90],
239
+ ["\u0261", 92],
240
+ ["\u0265", 99],
241
+ ["\u0268", 101],
242
+ ["\u026A", 102],
243
+ ["\u029D", 103],
244
+ ["\u026F", 110],
245
+ ["\u0270", 111],
246
+ ["\u014B", 112],
247
+ ["\u0273", 113],
248
+ ["\u0272", 114],
249
+ ["\u0274", 115],
250
+ ["\xF8", 116],
251
+ ["\u0278", 118],
252
+ ["\u03B8", 119],
253
+ ["\u0153", 120],
254
+ ["\u0279", 123],
255
+ ["\u027E", 125],
256
+ ["\u027B", 126],
257
+ ["\u0281", 128],
258
+ ["\u027D", 129],
259
+ ["\u0282", 130],
260
+ ["\u0283", 131],
261
+ ["\u0288", 132],
262
+ ["\u02A7", 133],
263
+ ["\u028A", 135],
264
+ ["\u028B", 136],
265
+ ["\u028C", 138],
266
+ ["\u0263", 139],
267
+ ["\u0264", 140],
268
+ ["\u03C7", 142],
269
+ ["\u028E", 143],
270
+ ["\u0292", 147],
271
+ ["\u0294", 148],
272
+ ["\u02C8", 156],
273
+ ["\u02CC", 157],
274
+ ["\u02D0", 158],
275
+ ["\u02B0", 162],
276
+ ["\u02B2", 164],
277
+ ["\u2193", 169],
278
+ ["\u2192", 171],
279
+ ["\u2197", 172],
280
+ ["\u2198", 173],
281
+ ["\u1D7B", 177]
282
+ ]);
283
+
284
+ // ../aula-narration/src/aula-voice.ts
285
+ var AULA_VOICE_RELEASE = "v0.1.1";
286
+ var RELEASE_URL = `https://github.com/lucasavila00/aula-voice/releases/download/${AULA_VOICE_RELEASE}`;
287
+ var AULA_VOICE_FILES = {
288
+ model: {
289
+ path: "model.safetensors",
290
+ bytes: 33489768,
291
+ sha256: "a15b9b378ee1e7d24004a4f5ff6ab03459fadec71d0acdf02d0e04034edde44a"
292
+ },
293
+ config: {
294
+ path: "config.json",
295
+ bytes: 2346,
296
+ sha256: "e5ea44e7d8ef2fe114725162aa68a4e57f1525cf4c206f9ac2f2db70ed051909"
297
+ }
298
+ };
299
+ var AULA_VOICE_WEIGHTS = {
300
+ path: "aula-voice.avw",
301
+ bytes: 33478208,
302
+ sha256: "b382770c55637371fd5f0eda9f7f5a9b39572c8715d24149bfbba4d8c64ac951"
303
+ };
304
+ var SERVER_WEIGHTS_PATH = `/models/${AULA_VOICE_WEIGHTS.path}`;
305
+ var aulaVoiceUrl = (file) => `${RELEASE_URL}/${file.path}`;
306
+ var VOICE = 0;
307
+ var SAMPLE_RATE = 24e3;
308
+ var HOP = 300;
309
+ var MAX_TOKENS = 250;
310
+ var LEAD = 16;
311
+ var PEAK = 0.99;
312
+ function limited(audio) {
313
+ let loudest = 0;
314
+ for (const sample of audio) loudest = Math.max(loudest, Math.abs(sample));
315
+ if (loudest <= PEAK) return audio;
316
+ const scale = PEAK / loudest;
317
+ return audio.map((sample) => sample * scale);
318
+ }
319
+ async function layout(parts, text, speed, audio) {
320
+ const batches = await batchesOf(parts.phonemize, text, MAX_TOKENS);
321
+ if (!batches.length) throw new Error(`Nothing to say: ${JSON.stringify(text)} has no phonemes`);
322
+ const pieces = [];
323
+ const timings = [];
324
+ let offset = 0;
325
+ for (const [index, batch] of batches.entries()) {
326
+ const { ids, known } = tokenize(KOKORO_VOCAB, batch);
327
+ if (!ids.length) throw new Error(`No phonemes of ${JSON.stringify(batch)} are in the model's token table`);
328
+ const padded = [0, ...ids, 0];
329
+ const spoken = audio ? parts.model.speak(padded, VOICE, speed) : { audio: null, durations: parts.model.durations(padded, VOICE, speed) };
330
+ const edges = [0];
331
+ for (let i = 0; i < spoken.durations.length; i++) edges.push((edges[i] ?? 0) + Number(spoken.durations[i]) * HOP);
332
+ const head = Math.max((edges[1] ?? 0) - LEAD * HOP, 0);
333
+ const tail = edges.at(-2) ?? head;
334
+ known.forEach((phoneme, i) => {
335
+ const start = (edges[i + 1] ?? head) - head + offset;
336
+ const end = (edges[i + 2] ?? tail) - head + offset;
337
+ timings.push({ phoneme, start: start / SAMPLE_RATE, end: end / SAMPLE_RATE });
338
+ });
339
+ const pause = index < batches.length - 1 ? Math.floor(pauseAfter(batch) * SAMPLE_RATE) : 0;
340
+ pieces.push({ audio: spoken.audio?.subarray(head, tail) ?? null, length: tail - head, pause });
341
+ offset += tail - head + pause;
342
+ }
343
+ return { pieces, total: offset, words: await timesOfWords(parts.phonemize, text, timings) };
344
+ }
345
+ async function speakAulaVoice(parts, text, speed) {
346
+ const { pieces, total, words } = await layout(parts, text, speed, true);
347
+ const samples = new Float32Array(total);
348
+ let offset = 0;
349
+ for (const piece of pieces) {
350
+ if (piece.audio) samples.set(piece.audio, offset);
351
+ offset += piece.length + piece.pause;
352
+ }
353
+ return { samples: limited(samples), sampleRate: SAMPLE_RATE, words };
354
+ }
355
+ async function timeAulaVoice(parts, text, speed) {
356
+ const { total, words } = await layout(parts, text, speed, false);
357
+ return { samples: total, sampleRate: SAMPLE_RATE, words };
358
+ }
359
+
360
+ // ../aula-narration/src/avw.ts
361
+ var FIXED = {
362
+ sample_rate: 24e3,
363
+ hop: 300,
364
+ n_fft: 1200,
365
+ channels: 192,
366
+ heads: 4,
367
+ feedforward: 640,
368
+ kernel: 7,
369
+ encoder_layers: 4,
370
+ prosody_layers: 2,
371
+ acoustic_layers: 5,
372
+ predictor_channels: 128,
373
+ head_channels: 256,
374
+ head_inner: 768,
375
+ head_kernel: 7
376
+ };
377
+ function stack(prefix, layers) {
378
+ const names = [];
379
+ for (let b = 0; b < layers; b++) {
380
+ const p = `${prefix}.blocks.${String(b)}`;
381
+ for (const part of [
382
+ "norm1.weight",
383
+ "norm1.bias",
384
+ "attention.qkv.weight",
385
+ "attention.qkv.bias",
386
+ "attention.out.weight",
387
+ "attention.out.bias",
388
+ "norm2.weight",
389
+ "norm2.bias",
390
+ "depthwise.weight",
391
+ "depthwise.bias",
392
+ "expand.weight",
393
+ "expand.bias",
394
+ "project.weight",
395
+ "project.bias"
396
+ ]) {
397
+ names.push(`${p}.${part}`);
398
+ }
399
+ }
400
+ return [...names, `${prefix}.norm.weight`, `${prefix}.norm.bias`];
401
+ }
402
+ function order(headBlocks) {
403
+ const predictor = ["conv1", "norm1", "conv2", "norm2", "out"].flatMap((part) => [
404
+ `duration.${part}.weight`,
405
+ `duration.${part}.bias`
406
+ ]);
407
+ const head = ["head.embed.weight", "head.embed.bias", "head.norm_in.weight", "head.norm_in.bias"];
408
+ for (let b = 0; b < headBlocks; b++) {
409
+ const p = `head.blocks.${String(b)}`;
410
+ for (const part of ["depthwise", "norm", "expand", "project"])
411
+ head.push(`${p}.${part}.weight`, `${p}.${part}.bias`);
412
+ head.push(`${p}.gamma`);
413
+ }
414
+ head.push("head.norm_out.weight", "head.norm_out.bias", "head.out.weight", "head.out.bias");
415
+ return [
416
+ "tokens.weight",
417
+ "voices.weight",
418
+ ...stack("encoder", 4),
419
+ ...predictor,
420
+ "frame_voices.weight",
421
+ "frame_position.weight",
422
+ "frame_position.bias",
423
+ ...stack("prosody_stack", 2),
424
+ "prosody_head.weight",
425
+ "prosody_head.bias",
426
+ "prosody_projection.weight",
427
+ "prosody_projection.bias",
428
+ ...stack("acoustic_stack", 5),
429
+ ...head,
430
+ "vowel_tokens"
431
+ ];
432
+ }
433
+ var isCount = (value) => Number.isInteger(value) && Number(value) >= 0;
434
+ function counts(value) {
435
+ if (!Array.isArray(value)) return null;
436
+ const out = [];
437
+ for (const item of value) {
438
+ if (!isCount(item)) return null;
439
+ out.push(item);
440
+ }
441
+ return out;
442
+ }
443
+ var pad = (n) => Math.ceil(n / 16) * 16;
444
+ function field(value, key) {
445
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
446
+ return Object.entries(value).find(([k]) => k === key)?.[1];
447
+ }
448
+ function readSafetensors(file) {
449
+ if (file.length < 8) throw new Error("model.safetensors is truncated in its header length");
450
+ const view = new DataView(file.buffer, file.byteOffset, file.byteLength);
451
+ const length = Number(view.getBigUint64(0, true));
452
+ if (8 + length > file.length) throw new Error("model.safetensors is truncated in its header");
453
+ const header = JSON.parse(new TextDecoder().decode(file.subarray(8, 8 + length)));
454
+ if (typeof header !== "object" || header === null || Array.isArray(header)) {
455
+ throw new Error("the header of model.safetensors is not an object");
456
+ }
457
+ const data = file.subarray(8 + length);
458
+ const tensors = /* @__PURE__ */ new Map();
459
+ for (const [name, entry] of Object.entries(header)) {
460
+ if (name === "__metadata__") continue;
461
+ const shape = counts(field(entry, "shape"));
462
+ const offsets = counts(field(entry, "data_offsets"));
463
+ if (field(entry, "dtype") !== "F32") throw new Error(`the tensor "${name}" is not F32`);
464
+ if (!shape || !offsets) throw new Error(`the tensor "${name}" has no shape or data offsets`);
465
+ const [start = 0, end = 0] = offsets;
466
+ const count = shape.reduce((a, b) => a * b, 1);
467
+ if (offsets.length !== 2 || end - start !== count * 4 || end > data.length) {
468
+ throw new Error(`the data offsets of "${name}" do not fit its shape or the file`);
469
+ }
470
+ tensors.set(name, { shape, bytes: data.subarray(start, end) });
471
+ }
472
+ return tensors;
473
+ }
474
+ function engineLayout(name, raw) {
475
+ const { shape, bytes } = raw;
476
+ const out = new Uint8Array(bytes.length);
477
+ const move = (to, from) => {
478
+ out.set(bytes.subarray(from * 4, from * 4 + 4), to * 4);
479
+ };
480
+ const embedding = name.endsWith("tokens.weight") || name.endsWith("voices.weight");
481
+ const [a = 0, b = 0, c = 0] = shape;
482
+ if (shape.length === 3 && b === 1 && name.includes("depthwise")) {
483
+ for (let ch = 0; ch < a; ch++) for (let k = 0; k < c; k++) move(k * a + ch, ch * c + k);
484
+ return { shape: [c, a], bytes: out };
485
+ }
486
+ if (shape.length === 3) {
487
+ for (let o = 0; o < a; o++) {
488
+ for (let i = 0; i < b; i++) for (let k = 0; k < c; k++) move((k * b + i) * a + o, (o * b + i) * c + k);
489
+ }
490
+ return { shape: [c, b, a], bytes: out };
491
+ }
492
+ if (shape.length === 2 && !embedding) {
493
+ for (let o = 0; o < a; o++) for (let i = 0; i < b; i++) move(i * a + o, o * b + i);
494
+ return { shape: [b, a], bytes: out };
495
+ }
496
+ return raw;
497
+ }
498
+ function studentWeightFile(model, config) {
499
+ const json = JSON.parse(new TextDecoder().decode(config));
500
+ if (field(json, "format") !== "aula-voice-raw" || field(json, "format_version") !== 1) {
501
+ throw new Error('config.json is not of the format "aula-voice-raw", version 1');
502
+ }
503
+ const settings = field(json, "student_config");
504
+ for (const [key, value] of Object.entries(FIXED)) {
505
+ if (field(settings, key) !== value) {
506
+ throw new Error(
507
+ `config.json has ${key} ${JSON.stringify(field(settings, key))}; the engine needs ${String(value)}`
508
+ );
509
+ }
510
+ }
511
+ const tensors = readSafetensors(model);
512
+ const tokens2 = tensors.get("tokens.weight");
513
+ const voices = tensors.get("voices.weight");
514
+ if (!tokens2 || !voices) throw new Error("model.safetensors has no tokens.weight or voices.weight");
515
+ const [vocab = 0, channels = 0] = tokens2.shape;
516
+ const headBlocks = new Set(
517
+ [...tensors.keys()].filter((n) => n.startsWith("head.blocks.")).map((n) => n.split(".")[2])
518
+ ).size;
519
+ if (field(settings, "vocab_size") !== vocab || field(settings, "head_blocks") !== headBlocks) {
520
+ throw new Error("config.json does not match the tensors of model.safetensors (vocab_size, head_blocks)");
521
+ }
522
+ const vowelIds = counts(field(field(json, "tokens"), "vowel_ids"));
523
+ if (!vowelIds || vowelIds.some((id) => id >= vocab)) {
524
+ throw new Error(`config.json's tokens.vowel_ids must be token ids below ${String(vocab)}`);
525
+ }
526
+ const vowels = new Uint8Array(vocab * 4);
527
+ for (const id of vowelIds) vowels.set(new Uint8Array(Float32Array.of(1).buffer), id * 4);
528
+ const names = order(headBlocks);
529
+ const unused = [...tensors.keys()].filter((name) => !names.includes(name));
530
+ if (unused.length)
531
+ throw new Error(`model.safetensors has tensors that the student does not use: ${unused.join(", ")}`);
532
+ const laid = names.map((name) => {
533
+ if (name === "vowel_tokens") return [name, { shape: [vocab], bytes: vowels }];
534
+ const raw = tensors.get(name);
535
+ if (!raw) throw new Error(`model.safetensors has no tensor "${name}"`);
536
+ return [`model.${name}`, engineLayout(name, raw)];
537
+ });
538
+ const list = laid.map(([name, raw]) => `["${name}", [${raw.shape.join(", ")}]]`).join(", ");
539
+ const header = new TextEncoder().encode(
540
+ `{"kind": "student", "dtype": "f32", "config": {"vocab": ${String(vocab)}, "voices": ${String(voices.shape[0] ?? 0)}, "channels": ${String(channels)}, "head_blocks": ${String(headBlocks)}}, "tensors": [${list}]}`
541
+ );
542
+ const size = laid.reduce((total, [, raw]) => total + pad(raw.bytes.length), pad(8 + header.length));
543
+ const file = new Uint8Array(size);
544
+ file.set(new TextEncoder().encode("AVW1"));
545
+ new DataView(file.buffer).setUint32(4, header.length, true);
546
+ file.set(header, 8);
547
+ let at = pad(8 + header.length);
548
+ for (const [, raw] of laid) {
549
+ file.set(raw.bytes, at);
550
+ at += pad(raw.bytes.length);
551
+ }
552
+ return file;
553
+ }
554
+
555
+ // ../aula-narration/src/phonemize.ts
556
+ import { loadEngine } from "@beff/aula/run";
557
+ import { phonemize } from "@beff/aula/text";
558
+ function britishPhonemizer(vocab) {
559
+ return async (text) => {
560
+ await loadEngine();
561
+ return Array.from(phonemize(text)).filter((phoneme) => vocab.has(phoneme)).join("").trim();
562
+ };
563
+ }
564
+
565
+ export {
566
+ tokenBatches,
567
+ KOKORO_VOCAB,
568
+ AULA_VOICE_RELEASE,
569
+ AULA_VOICE_FILES,
570
+ AULA_VOICE_WEIGHTS,
571
+ SERVER_WEIGHTS_PATH,
572
+ aulaVoiceUrl,
573
+ speakAulaVoice,
574
+ timeAulaVoice,
575
+ studentWeightFile,
576
+ britishPhonemizer
577
+ };