@beff/aula-cli 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.
Files changed (40) hide show
  1. package/README.md +10 -2
  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-3IBMAZRS.js +21 -0
  10. package/dist/src/chunk-EYXQ2I7K.js +604 -0
  11. package/dist/src/chunk-GFCJYE75.js +42 -0
  12. package/dist/src/chunk-KLE5UOUB.js +57 -0
  13. package/dist/src/chunk-OMBYV6CK.js +1063 -0
  14. package/dist/src/chunk-PYRORQA5.js +88 -0
  15. package/dist/src/chunk-SDFXIMLW.js +1083 -0
  16. package/dist/src/chunk-UREQAEFC.js +491 -0
  17. package/dist/src/chunk-X3HJY34X.js +81 -0
  18. package/dist/src/cli.js +269 -0
  19. package/dist/src/commands-VDGWDVWT.js +28 -0
  20. package/dist/src/problems-OGUR4BLZ.js +12 -0
  21. package/dist/src/project-M63R4ENB.js +11 -0
  22. package/dist/src/render-child.js +3771 -0
  23. package/dist/src/run-CY72QGZJ.js +127 -0
  24. package/dist/src/server-ZG6K7Z7H.js +280 -0
  25. package/dist/web/app/assets/__vite-browser-external-Bbi05A7N.js +1 -0
  26. package/dist/web/app/assets/__vite-browser-external-BtQTJ51O.js +1 -0
  27. package/dist/web/app/assets/aula-method.js +1 -0
  28. package/dist/web/app/assets/aula-voice-worker-BL6WcrSe.js +52 -0
  29. package/dist/web/app/assets/aula.core-BtiPQSZi.wasm +0 -0
  30. package/dist/web/app/assets/aula.core5-BdGB-M10.wasm +0 -0
  31. package/dist/web/app/assets/aula.js +1 -0
  32. package/dist/web/app/assets/build-worker.js +697 -0
  33. package/dist/web/app/assets/esbuild-BaXVPFT2.wasm +0 -0
  34. package/dist/web/app/assets/index-BVQqteYG.js +53 -0
  35. package/dist/web/app/assets/index-CS60sOpp.css +2 -0
  36. package/dist/web/app/assets/protocol-Ds4jI5bY.js +15 -0
  37. package/dist/web/app/assets/rolldown-runtime-BLXQ4ufn.js +1 -0
  38. package/dist/web/app/assets/src-BbJ5r410.js +25 -0
  39. package/dist/web/app/index.html +15 -0
  40. package/package.json +26 -3
@@ -0,0 +1,604 @@
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 = { name: "bf_emma", index: 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.index, speed) : { audio: null, durations: parts.model.durations(padded, VOICE.index, 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
+ var aulaVoiceId = (backend) => `aula-voice@${AULA_VOICE_RELEASE}+${AULA_VOICE_WEIGHTS.sha256.slice(0, 12)}/${VOICE.name}/${backend}`;
360
+
361
+ // ../aula-narration/src/avw.ts
362
+ var FIXED = {
363
+ sample_rate: 24e3,
364
+ hop: 300,
365
+ n_fft: 1200,
366
+ channels: 192,
367
+ heads: 4,
368
+ feedforward: 640,
369
+ kernel: 7,
370
+ encoder_layers: 4,
371
+ prosody_layers: 2,
372
+ acoustic_layers: 5,
373
+ predictor_channels: 128,
374
+ head_channels: 256,
375
+ head_inner: 768,
376
+ head_kernel: 7
377
+ };
378
+ function stack(prefix, layers) {
379
+ const names = [];
380
+ for (let b = 0; b < layers; b++) {
381
+ const p = `${prefix}.blocks.${String(b)}`;
382
+ for (const part of [
383
+ "norm1.weight",
384
+ "norm1.bias",
385
+ "attention.qkv.weight",
386
+ "attention.qkv.bias",
387
+ "attention.out.weight",
388
+ "attention.out.bias",
389
+ "norm2.weight",
390
+ "norm2.bias",
391
+ "depthwise.weight",
392
+ "depthwise.bias",
393
+ "expand.weight",
394
+ "expand.bias",
395
+ "project.weight",
396
+ "project.bias"
397
+ ]) {
398
+ names.push(`${p}.${part}`);
399
+ }
400
+ }
401
+ return [...names, `${prefix}.norm.weight`, `${prefix}.norm.bias`];
402
+ }
403
+ function order(headBlocks) {
404
+ const predictor = ["conv1", "norm1", "conv2", "norm2", "out"].flatMap((part) => [
405
+ `duration.${part}.weight`,
406
+ `duration.${part}.bias`
407
+ ]);
408
+ const head = ["head.embed.weight", "head.embed.bias", "head.norm_in.weight", "head.norm_in.bias"];
409
+ for (let b = 0; b < headBlocks; b++) {
410
+ const p = `head.blocks.${String(b)}`;
411
+ for (const part of ["depthwise", "norm", "expand", "project"])
412
+ head.push(`${p}.${part}.weight`, `${p}.${part}.bias`);
413
+ head.push(`${p}.gamma`);
414
+ }
415
+ head.push("head.norm_out.weight", "head.norm_out.bias", "head.out.weight", "head.out.bias");
416
+ return [
417
+ "tokens.weight",
418
+ "voices.weight",
419
+ ...stack("encoder", 4),
420
+ ...predictor,
421
+ "frame_voices.weight",
422
+ "frame_position.weight",
423
+ "frame_position.bias",
424
+ ...stack("prosody_stack", 2),
425
+ "prosody_head.weight",
426
+ "prosody_head.bias",
427
+ "prosody_projection.weight",
428
+ "prosody_projection.bias",
429
+ ...stack("acoustic_stack", 5),
430
+ ...head,
431
+ "vowel_tokens"
432
+ ];
433
+ }
434
+ var isCount = (value) => Number.isInteger(value) && Number(value) >= 0;
435
+ function counts(value) {
436
+ if (!Array.isArray(value)) return null;
437
+ const out = [];
438
+ for (const item of value) {
439
+ if (!isCount(item)) return null;
440
+ out.push(item);
441
+ }
442
+ return out;
443
+ }
444
+ var pad = (n) => Math.ceil(n / 16) * 16;
445
+ function field(value, key) {
446
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
447
+ return Object.entries(value).find(([k]) => k === key)?.[1];
448
+ }
449
+ function readSafetensors(file) {
450
+ if (file.length < 8) throw new Error("model.safetensors is truncated in its header length");
451
+ const view = new DataView(file.buffer, file.byteOffset, file.byteLength);
452
+ const length = Number(view.getBigUint64(0, true));
453
+ if (8 + length > file.length) throw new Error("model.safetensors is truncated in its header");
454
+ const header = JSON.parse(new TextDecoder().decode(file.subarray(8, 8 + length)));
455
+ if (typeof header !== "object" || header === null || Array.isArray(header)) {
456
+ throw new Error("the header of model.safetensors is not an object");
457
+ }
458
+ const data = file.subarray(8 + length);
459
+ const tensors = /* @__PURE__ */ new Map();
460
+ for (const [name, entry] of Object.entries(header)) {
461
+ if (name === "__metadata__") continue;
462
+ const shape = counts(field(entry, "shape"));
463
+ const offsets = counts(field(entry, "data_offsets"));
464
+ if (field(entry, "dtype") !== "F32") throw new Error(`the tensor "${name}" is not F32`);
465
+ if (!shape || !offsets) throw new Error(`the tensor "${name}" has no shape or data offsets`);
466
+ const [start = 0, end = 0] = offsets;
467
+ const count = shape.reduce((a, b) => a * b, 1);
468
+ if (offsets.length !== 2 || end - start !== count * 4 || end > data.length) {
469
+ throw new Error(`the data offsets of "${name}" do not fit its shape or the file`);
470
+ }
471
+ tensors.set(name, { shape, bytes: data.subarray(start, end) });
472
+ }
473
+ return tensors;
474
+ }
475
+ function engineLayout(name, raw) {
476
+ const { shape, bytes } = raw;
477
+ const out = new Uint8Array(bytes.length);
478
+ const move = (to, from) => {
479
+ out.set(bytes.subarray(from * 4, from * 4 + 4), to * 4);
480
+ };
481
+ const embedding = name.endsWith("tokens.weight") || name.endsWith("voices.weight");
482
+ const [a = 0, b = 0, c = 0] = shape;
483
+ if (shape.length === 3 && b === 1 && name.includes("depthwise")) {
484
+ for (let ch = 0; ch < a; ch++) for (let k = 0; k < c; k++) move(k * a + ch, ch * c + k);
485
+ return { shape: [c, a], bytes: out };
486
+ }
487
+ if (shape.length === 3) {
488
+ for (let o = 0; o < a; o++) {
489
+ 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);
490
+ }
491
+ return { shape: [c, b, a], bytes: out };
492
+ }
493
+ if (shape.length === 2 && !embedding) {
494
+ for (let o = 0; o < a; o++) for (let i = 0; i < b; i++) move(i * a + o, o * b + i);
495
+ return { shape: [b, a], bytes: out };
496
+ }
497
+ return raw;
498
+ }
499
+ function studentWeightFile(model, config) {
500
+ const json = JSON.parse(new TextDecoder().decode(config));
501
+ if (field(json, "format") !== "aula-voice-raw" || field(json, "format_version") !== 1) {
502
+ throw new Error('config.json is not of the format "aula-voice-raw", version 1');
503
+ }
504
+ const settings = field(json, "student_config");
505
+ for (const [key, value] of Object.entries(FIXED)) {
506
+ if (field(settings, key) !== value) {
507
+ throw new Error(
508
+ `config.json has ${key} ${JSON.stringify(field(settings, key))}; the engine needs ${String(value)}`
509
+ );
510
+ }
511
+ }
512
+ const tensors = readSafetensors(model);
513
+ const tokens2 = tensors.get("tokens.weight");
514
+ const voices = tensors.get("voices.weight");
515
+ if (!tokens2 || !voices) throw new Error("model.safetensors has no tokens.weight or voices.weight");
516
+ const [vocab = 0, channels = 0] = tokens2.shape;
517
+ const headBlocks = new Set(
518
+ [...tensors.keys()].filter((n) => n.startsWith("head.blocks.")).map((n) => n.split(".")[2])
519
+ ).size;
520
+ if (field(settings, "vocab_size") !== vocab || field(settings, "head_blocks") !== headBlocks) {
521
+ throw new Error("config.json does not match the tensors of model.safetensors (vocab_size, head_blocks)");
522
+ }
523
+ const vowelIds = counts(field(field(json, "tokens"), "vowel_ids"));
524
+ if (!vowelIds || vowelIds.some((id) => id >= vocab)) {
525
+ throw new Error(`config.json's tokens.vowel_ids must be token ids below ${String(vocab)}`);
526
+ }
527
+ const vowels = new Uint8Array(vocab * 4);
528
+ for (const id of vowelIds) vowels.set(new Uint8Array(Float32Array.of(1).buffer), id * 4);
529
+ const names = order(headBlocks);
530
+ const unused = [...tensors.keys()].filter((name) => !names.includes(name));
531
+ if (unused.length)
532
+ throw new Error(`model.safetensors has tensors that the student does not use: ${unused.join(", ")}`);
533
+ const laid = names.map((name) => {
534
+ if (name === "vowel_tokens") return [name, { shape: [vocab], bytes: vowels }];
535
+ const raw = tensors.get(name);
536
+ if (!raw) throw new Error(`model.safetensors has no tensor "${name}"`);
537
+ return [`model.${name}`, engineLayout(name, raw)];
538
+ });
539
+ const list = laid.map(([name, raw]) => `["${name}", [${raw.shape.join(", ")}]]`).join(", ");
540
+ const header = new TextEncoder().encode(
541
+ `{"kind": "student", "dtype": "f32", "config": {"vocab": ${String(vocab)}, "voices": ${String(voices.shape[0] ?? 0)}, "channels": ${String(channels)}, "head_blocks": ${String(headBlocks)}}, "tensors": [${list}]}`
542
+ );
543
+ const size = laid.reduce((total, [, raw]) => total + pad(raw.bytes.length), pad(8 + header.length));
544
+ const file = new Uint8Array(size);
545
+ file.set(new TextEncoder().encode("AVW1"));
546
+ new DataView(file.buffer).setUint32(4, header.length, true);
547
+ file.set(header, 8);
548
+ let at = pad(8 + header.length);
549
+ for (const [, raw] of laid) {
550
+ file.set(raw.bytes, at);
551
+ at += pad(raw.bytes.length);
552
+ }
553
+ return file;
554
+ }
555
+
556
+ // ../aula-narration/src/narrator.ts
557
+ function once(load) {
558
+ let loading = null;
559
+ return async () => {
560
+ if (loading) return loading;
561
+ const started = load();
562
+ loading = started;
563
+ let loaded = false;
564
+ try {
565
+ const value = await started;
566
+ loaded = true;
567
+ return value;
568
+ } finally {
569
+ if (!loaded) loading = null;
570
+ }
571
+ };
572
+ }
573
+ function aulaVoiceNarrator(backend, load) {
574
+ const model = once(load);
575
+ return {
576
+ id: aulaVoiceId(backend),
577
+ speak: async (text, speed) => speakAulaVoice(await model(), text, speed),
578
+ time: async (text, speed) => timeAulaVoice(await model(), text, speed),
579
+ onStatus: () => void 0
580
+ };
581
+ }
582
+
583
+ // ../aula-narration/src/phonemize.ts
584
+ import { loadEngine } from "@beff/aula/run";
585
+ import { phonemize } from "@beff/aula/text";
586
+ function britishPhonemizer(vocab) {
587
+ return async (text) => {
588
+ await loadEngine();
589
+ return Array.from(phonemize(text)).filter((phoneme) => vocab.has(phoneme)).join("").trim();
590
+ };
591
+ }
592
+
593
+ export {
594
+ tokenBatches,
595
+ KOKORO_VOCAB,
596
+ AULA_VOICE_RELEASE,
597
+ AULA_VOICE_FILES,
598
+ AULA_VOICE_WEIGHTS,
599
+ SERVER_WEIGHTS_PATH,
600
+ aulaVoiceUrl,
601
+ studentWeightFile,
602
+ aulaVoiceNarrator,
603
+ britishPhonemizer
604
+ };
@@ -0,0 +1,42 @@
1
+ import {
2
+ run
3
+ } from "./chunk-2XGNOG2U.js";
4
+
5
+ // src/media.ts
6
+ import path from "node:path";
7
+ var VIDEO = { width: 1280, height: 720, fps: 30 };
8
+ async function ffmpeg(capabilities, args) {
9
+ const ran = await run(capabilities, "ffmpeg", ["-hide_banner", "-loglevel", "error", "-nostdin", "-y", ...args]);
10
+ if (ran.code !== 0) throw new Error(`ffmpeg failed: ${ran.stderr.trim()}`);
11
+ }
12
+ async function duration(capabilities, file) {
13
+ const { stderr } = await run(capabilities, "ffmpeg", ["-i", file]);
14
+ const stamp = stderr.split("Duration: ")[1]?.split(",")[0];
15
+ if (stamp === void 0) throw new Error(`${file}: ffmpeg reports no duration`);
16
+ const [h, m, s, ...rest] = stamp.split(":").map((p) => Number(p.trim()));
17
+ if (h === void 0 || m === void 0 || s === void 0 || rest.length || [h, m, s].some(Number.isNaN)) {
18
+ throw new Error(`${file}: unreadable duration ${stamp}`);
19
+ }
20
+ return h * 3600 + m * 60 + s;
21
+ }
22
+ var signed = (x) => `${x >= 0 ? "+" : ""}${x.toFixed(2)}`;
23
+ async function assemble(capabilities, options) {
24
+ const concat = path.join(options.work, "concat.txt");
25
+ await capabilities.fs.writeFile(concat, options.clips.map((v) => `file '${v}'
26
+ `).join(""));
27
+ const join = ["-f", "concat", "-safe", "0", "-i", concat, "-i", options.audio, "-map", "0:v:0", "-map", "1:a:0"];
28
+ const codecs = ["-c:v", "copy", "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart"];
29
+ await ffmpeg(capabilities, [...join, ...codecs, options.out]);
30
+ const video = await duration(capabilities, options.out);
31
+ const diff = video - options.seconds;
32
+ capabilities.log.out(`video ${video.toFixed(2)}s narration ${options.seconds.toFixed(2)}s diff ${signed(diff)}s`);
33
+ if (Math.abs(diff) > 1 / VIDEO.fps) {
34
+ throw new Error(`Out of sync: video and narration differ by more than one frame (${options.out})`);
35
+ }
36
+ }
37
+
38
+ export {
39
+ VIDEO,
40
+ ffmpeg,
41
+ assemble
42
+ };
@@ -0,0 +1,57 @@
1
+ import {
2
+ ObjectRuntype,
3
+ OptionalFieldRuntype,
4
+ RefRuntype,
5
+ TypeofRuntype,
6
+ buildParsers
7
+ } from "./chunk-SDFXIMLW.js";
8
+
9
+ // generated/parser.js
10
+ var RequiredStringFormats = [];
11
+ var RequiredNumberFormats = [];
12
+ var namedRuntypes = {};
13
+ var stringFormatters = {};
14
+ var numberFormatters = {};
15
+ var direct_hoist_0 = new RefRuntype(void 0, "SpeakRequest", namedRuntypes);
16
+ var direct_hoist_1 = new RefRuntype(void 0, "TokensLine", namedRuntypes);
17
+ var direct_hoist_2 = new TypeofRuntype(void 0, "number");
18
+ var direct_hoist_3 = new TypeofRuntype(void 0, "string");
19
+ var direct_hoist_4 = new ObjectRuntype({
20
+ "description": "`POST /speak` and `POST /time`: the text, and its speed (1 is normal; headings use 0.9)."
21
+ }, {
22
+ "speed": direct_hoist_2,
23
+ "text": direct_hoist_3
24
+ }, []);
25
+ var direct_hoist_5 = new ObjectRuntype({
26
+ "description": "One input line of `aula tokens`: a text, and an optional id that the output line repeats."
27
+ }, {
28
+ "id": new OptionalFieldRuntype(direct_hoist_3),
29
+ "text": direct_hoist_3
30
+ }, []);
31
+ Object.assign(namedRuntypes, {
32
+ "SpeakRequest": direct_hoist_4,
33
+ "TokensLine": direct_hoist_5
34
+ });
35
+ var buildParsersInput = {
36
+ "SpeakRequest": direct_hoist_0,
37
+ "TokensLine": direct_hoist_1
38
+ };
39
+ var parser_default = {
40
+ buildParsers: (args) => buildParsers(
41
+ {
42
+ parsers: buildParsersInput,
43
+ stringFormatters,
44
+ numberFormatters,
45
+ requiredStringFormats: RequiredStringFormats,
46
+ requiredNumberFormats: RequiredNumberFormats
47
+ },
48
+ args
49
+ )
50
+ };
51
+
52
+ // src/parsers.ts
53
+ var Parsers = parser_default.buildParsers();
54
+
55
+ export {
56
+ Parsers
57
+ };