@biunow/agent-biutalk 0.0.0-stage → 1.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 (227) hide show
  1. package/bin/server.js +355 -0
  2. package/engine/AGENTS.md +1414 -0
  3. package/engine/CLAUDE.md +1 -0
  4. package/engine/LICENSE +21 -0
  5. package/engine/README.md +216 -0
  6. package/engine/bin/explainroo.js +19 -0
  7. package/engine/dev/audio-lab.mjs +268 -0
  8. package/engine/docs/media/contact-sheet.jpg +0 -0
  9. package/engine/docs/media/dns-poster.jpg +0 -0
  10. package/engine/docs/media/intro-poster.jpg +0 -0
  11. package/engine/docs/media/logo-dark.png +0 -0
  12. package/engine/docs/media/logo-light.png +0 -0
  13. package/engine/docs/media/looks-dark.webp +0 -0
  14. package/engine/docs/media/looks-light.webp +0 -0
  15. package/engine/docs/media/product-demo.webp +0 -0
  16. package/engine/docs/media/rebase-poster.jpg +0 -0
  17. package/engine/docs/media/sizes-dark.webp +0 -0
  18. package/engine/docs/media/sizes-light.webp +0 -0
  19. package/engine/engine/audio/dsp.js +69 -0
  20. package/engine/engine/audio/instruments.js +147 -0
  21. package/engine/engine/audio/music.js +576 -0
  22. package/engine/engine/audio/pcm.js +93 -0
  23. package/engine/engine/audio/rng.js +40 -0
  24. package/engine/engine/audio/sfx.js +287 -0
  25. package/engine/engine/audio/soundtrack.js +201 -0
  26. package/engine/engine/audio/synth.js +721 -0
  27. package/engine/engine/audio/theory.js +105 -0
  28. package/engine/engine/audio/wav.js +47 -0
  29. package/engine/engine/captions.js +131 -0
  30. package/engine/engine/clips.js +107 -0
  31. package/engine/engine/code.js +179 -0
  32. package/engine/engine/director.js +475 -0
  33. package/engine/engine/frame.html +135 -0
  34. package/engine/engine/icons/LICENSE-lucide.txt +43 -0
  35. package/engine/engine/icons/lucide-tags.json +1 -0
  36. package/engine/engine/icons/lucide.json +1 -0
  37. package/engine/engine/layout.js +69 -0
  38. package/engine/engine/pathdata.js +234 -0
  39. package/engine/engine/pen.js +240 -0
  40. package/engine/engine/player.html +67 -0
  41. package/engine/engine/player.js +219 -0
  42. package/engine/engine/readability.js +9 -0
  43. package/engine/engine/runtime.js +690 -0
  44. package/engine/engine/stage.js +2247 -0
  45. package/engine/engine/studio.html +216 -0
  46. package/engine/engine/text.js +81 -0
  47. package/engine/engine/themes.js +360 -0
  48. package/engine/engine/transitions.js +161 -0
  49. package/engine/engine/ui.js +1042 -0
  50. package/engine/engine/upload.js +32 -0
  51. package/engine/engine/util.js +204 -0
  52. package/engine/examples/callbacks-to-async-await/code-versions.js +34 -0
  53. package/engine/examples/callbacks-to-async-await/scenes.js +106 -0
  54. package/engine/examples/callbacks-to-async-await/script.md +22 -0
  55. package/engine/examples/callbacks-to-async-await/video.json +16 -0
  56. package/engine/examples/circle-area/scenes.js +228 -0
  57. package/engine/examples/circle-area/script.md +37 -0
  58. package/engine/examples/circle-area/video.json +14 -0
  59. package/engine/examples/explainroo-intro/scenes.js +133 -0
  60. package/engine/examples/explainroo-intro/script.md +27 -0
  61. package/engine/examples/explainroo-intro/video.json +8 -0
  62. package/engine/examples/how-dns-works/scenes.js +130 -0
  63. package/engine/examples/how-dns-works/script.md +28 -0
  64. package/engine/examples/how-dns-works/video.json +8 -0
  65. package/engine/examples/leap-years/scenes.js +156 -0
  66. package/engine/examples/leap-years/script.md +25 -0
  67. package/engine/examples/leap-years/video.json +16 -0
  68. package/engine/examples/leap-years-ja/scenes.js +194 -0
  69. package/engine/examples/leap-years-ja/script.md +32 -0
  70. package/engine/examples/leap-years-ja/video.json +17 -0
  71. package/engine/examples/merge-vs-rebase/scenes.js +129 -0
  72. package/engine/examples/merge-vs-rebase/script.md +22 -0
  73. package/engine/examples/merge-vs-rebase/video.json +8 -0
  74. package/engine/examples/password-storage-zh/scenes.js +185 -0
  75. package/engine/examples/password-storage-zh/script.md +25 -0
  76. package/engine/examples/password-storage-zh/video.json +19 -0
  77. package/engine/examples/sqlite-demo/README.md +19 -0
  78. package/engine/examples/sqlite-demo/scenes.js +423 -0
  79. package/engine/examples/sqlite-demo/script.md +35 -0
  80. package/engine/examples/sqlite-demo/video.json +17 -0
  81. package/engine/examples/unspar-demo/assets/fonts/Figtree-400.woff2 +0 -0
  82. package/engine/examples/unspar-demo/assets/fonts/Figtree-500.woff2 +0 -0
  83. package/engine/examples/unspar-demo/assets/fonts/Figtree-600.woff2 +0 -0
  84. package/engine/examples/unspar-demo/assets/fonts/Figtree-700.woff2 +0 -0
  85. package/engine/examples/unspar-demo/assets/fonts/Figtree-OFL.txt +93 -0
  86. package/engine/examples/unspar-demo/assets/unspar-logo.svg +23 -0
  87. package/engine/examples/unspar-demo/scenes.js +367 -0
  88. package/engine/examples/unspar-demo/script.md +25 -0
  89. package/engine/examples/unspar-demo/video.json +21 -0
  90. package/engine/examples/why-is-the-sky-blue-es/scenes.js +160 -0
  91. package/engine/examples/why-is-the-sky-blue-es/script.md +22 -0
  92. package/engine/examples/why-is-the-sky-blue-es/video.json +15 -0
  93. package/engine/fonts/ArchitectsDaughter-400-latin-ext.woff2 +0 -0
  94. package/engine/fonts/ArchitectsDaughter-400-latin.woff2 +0 -0
  95. package/engine/fonts/CabinSketch-400-latin.woff2 +0 -0
  96. package/engine/fonts/CabinSketch-700-latin.woff2 +0 -0
  97. package/engine/fonts/InstrumentSerif-400-italic-latin-ext.woff2 +0 -0
  98. package/engine/fonts/InstrumentSerif-400-italic-latin.woff2 +0 -0
  99. package/engine/fonts/InstrumentSerif-400-normal-latin-ext.woff2 +0 -0
  100. package/engine/fonts/InstrumentSerif-400-normal-latin.woff2 +0 -0
  101. package/engine/fonts/Inter-400-latin-ext.woff2 +0 -0
  102. package/engine/fonts/Inter-400-latin.woff2 +0 -0
  103. package/engine/fonts/JetBrainsMono-400-latin-ext.woff2 +0 -0
  104. package/engine/fonts/JetBrainsMono-400-latin.woff2 +0 -0
  105. package/engine/fonts/Kalam-400-latin-ext.woff2 +0 -0
  106. package/engine/fonts/Kalam-400-latin.woff2 +0 -0
  107. package/engine/fonts/Kalam-700-latin-ext.woff2 +0 -0
  108. package/engine/fonts/Kalam-700-latin.woff2 +0 -0
  109. package/engine/fonts/NotoSansDevanagari-400.ttf +0 -0
  110. package/engine/fonts/NotoSansDevanagari-700.ttf +0 -0
  111. package/engine/fonts/PatrickHand-400-latin-ext.woff2 +0 -0
  112. package/engine/fonts/PatrickHand-400-latin.woff2 +0 -0
  113. package/engine/fonts/PlusJakartaSans-600-latin-ext.woff2 +0 -0
  114. package/engine/fonts/PlusJakartaSans-600-latin.woff2 +0 -0
  115. package/engine/fonts/SpaceGrotesk-500-latin-ext.woff2 +0 -0
  116. package/engine/fonts/SpaceGrotesk-500-latin.woff2 +0 -0
  117. package/engine/fonts/fonts.json +216 -0
  118. package/engine/fonts/licenses/ArchitectsDaughter-OFL.txt +93 -0
  119. package/engine/fonts/licenses/CabinSketch-OFL.txt +93 -0
  120. package/engine/fonts/licenses/InstrumentSerif-OFL.txt +93 -0
  121. package/engine/fonts/licenses/Inter-OFL.txt +93 -0
  122. package/engine/fonts/licenses/JetBrainsMono-OFL.txt +93 -0
  123. package/engine/fonts/licenses/Kalam-OFL.txt +93 -0
  124. package/engine/fonts/licenses/NotoSansDevanagari-OFL.txt +118 -0
  125. package/engine/fonts/licenses/PatrickHand-OFL.txt +93 -0
  126. package/engine/fonts/licenses/PlusJakartaSans-OFL.txt +93 -0
  127. package/engine/fonts/licenses/SpaceGrotesk-OFL.txt +93 -0
  128. package/engine/package-lock.json +1201 -0
  129. package/engine/package.json +67 -0
  130. package/engine/scripts/build-icons.mjs +74 -0
  131. package/engine/scripts/fetch-fonts.mjs +68 -0
  132. package/engine/skills/explainroo/SKILL.md +51 -0
  133. package/engine/src/align.js +357 -0
  134. package/engine/src/browser.js +121 -0
  135. package/engine/src/capture.js +315 -0
  136. package/engine/src/chapters.js +32 -0
  137. package/engine/src/cli.js +421 -0
  138. package/engine/src/clips.js +19 -0
  139. package/engine/src/elevenlabs.js +90 -0
  140. package/engine/src/env.js +16 -0
  141. package/engine/src/export.js +187 -0
  142. package/engine/src/ffmpeg.js +103 -0
  143. package/engine/src/fonts.js +86 -0
  144. package/engine/src/g2p.py +76 -0
  145. package/engine/src/images.js +151 -0
  146. package/engine/src/licenses/misaki-Apache-2.0.txt +201 -0
  147. package/engine/src/math.js +83 -0
  148. package/engine/src/models.js +161 -0
  149. package/engine/src/phonemes.js +162 -0
  150. package/engine/src/pipeline.js +63 -0
  151. package/engine/src/project.js +331 -0
  152. package/engine/src/qa.js +186 -0
  153. package/engine/src/recordings.js +89 -0
  154. package/engine/src/render.js +156 -0
  155. package/engine/src/script.js +266 -0
  156. package/engine/src/server.js +288 -0
  157. package/engine/src/subtitles.js +78 -0
  158. package/engine/src/timeline.js +55 -0
  159. package/engine/src/voice.js +240 -0
  160. package/engine/src/wav.js +98 -0
  161. package/engine/templates/starter/scenes.js +31 -0
  162. package/engine/templates/starter/script.md +14 -0
  163. package/engine/test/align.test.js +108 -0
  164. package/engine/test/brand.test.js +41 -0
  165. package/engine/test/browser.test.js +89 -0
  166. package/engine/test/camera-browser.test.js +225 -0
  167. package/engine/test/caption-phrases.test.js +35 -0
  168. package/engine/test/capture-browser.test.js +90 -0
  169. package/engine/test/capture-fixture.js +46 -0
  170. package/engine/test/capture.test.js +62 -0
  171. package/engine/test/chapters.test.js +41 -0
  172. package/engine/test/cjk-browser.test.js +101 -0
  173. package/engine/test/cjk.test.js +232 -0
  174. package/engine/test/cli-exit.test.js +25 -0
  175. package/engine/test/cli.test.js +116 -0
  176. package/engine/test/clips-browser.test.js +125 -0
  177. package/engine/test/clips.test.js +67 -0
  178. package/engine/test/code-morph-browser.test.js +99 -0
  179. package/engine/test/code-morph.test.js +110 -0
  180. package/engine/test/contrast-browser.test.js +63 -0
  181. package/engine/test/contrast.test.js +80 -0
  182. package/engine/test/director.test.js +316 -0
  183. package/engine/test/engine-pure.test.js +29 -0
  184. package/engine/test/export-browser.test.js +224 -0
  185. package/engine/test/export.test.js +96 -0
  186. package/engine/test/fixtures/capture.html +55 -0
  187. package/engine/test/formats-pace.test.js +104 -0
  188. package/engine/test/languages-browser.test.js +78 -0
  189. package/engine/test/languages.test.js +140 -0
  190. package/engine/test/looks-browser.test.js +109 -0
  191. package/engine/test/looks-preview.test.js +57 -0
  192. package/engine/test/looks.test.js +130 -0
  193. package/engine/test/math-browser.test.js +114 -0
  194. package/engine/test/math.test.js +54 -0
  195. package/engine/test/multi-size-browser.test.js +133 -0
  196. package/engine/test/multi-size.test.js +116 -0
  197. package/engine/test/phonemes.test.js +92 -0
  198. package/engine/test/readability-browser.test.js +36 -0
  199. package/engine/test/readability.test.js +20 -0
  200. package/engine/test/render-options.test.js +52 -0
  201. package/engine/test/script.test.js +67 -0
  202. package/engine/test/server.test.js +256 -0
  203. package/engine/test/stills-browser.test.js +70 -0
  204. package/engine/test/subtitles.test.js +83 -0
  205. package/engine/test/timeline.test.js +31 -0
  206. package/engine/test/transparent-browser.test.js +123 -0
  207. package/engine/test/ui-kit.test.js +96 -0
  208. package/engine/test/upload-browser.test.js +55 -0
  209. package/engine/test/voice-providers.test.js +338 -0
  210. package/lib/host.mjs +480 -0
  211. package/manifest.json +54 -0
  212. package/package.json +8 -4
  213. package/skills/biutalk/SKILL.md +21 -0
  214. package/studio/app.js +209 -0
  215. package/studio/assert-panel-permit.mjs +67 -0
  216. package/studio/composer.css +354 -0
  217. package/studio/composer.js +169 -0
  218. package/studio/index.html +82 -0
  219. package/studio/looks/blueprint.svg +21 -0
  220. package/studio/looks/chalk.svg +15 -0
  221. package/studio/looks/clean.svg +20 -0
  222. package/studio/looks/editorial.svg +18 -0
  223. package/studio/looks/midnight.svg +17 -0
  224. package/studio/looks/paper.svg +11 -0
  225. package/studio/select-menu.js +268 -0
  226. package/studio/styles.css +4 -0
  227. package/README.md +0 -3
@@ -0,0 +1,288 @@
1
+ // Local HTTP server for the engine pages, the project files and uploads from
2
+ // the page (rendered audio, stills and sheets). Binds to 127.0.0.1 only.
3
+ import http from 'node:http';
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { ensureFonts, languageFonts } from './fonts.js';
9
+ import { extractClip, VIDEO_FILE } from './clips.js';
10
+ import { typesetMath, mathHash, MAX_TEX_LENGTH } from './math.js';
11
+
12
+ export const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
13
+
14
+ const TYPES = {
15
+ '.html': 'text/html; charset=utf-8',
16
+ '.js': 'text/javascript; charset=utf-8',
17
+ '.mjs': 'text/javascript; charset=utf-8',
18
+ '.json': 'application/json; charset=utf-8',
19
+ '.css': 'text/css; charset=utf-8',
20
+ '.wav': 'audio/wav',
21
+ '.mp3': 'audio/mpeg',
22
+ '.woff2': 'font/woff2',
23
+ '.woff': 'font/woff',
24
+ '.ttf': 'font/ttf',
25
+ '.otf': 'font/otf',
26
+ '.png': 'image/png',
27
+ '.jpg': 'image/jpeg',
28
+ '.jpeg': 'image/jpeg',
29
+ '.webp': 'image/webp',
30
+ '.gif': 'image/gif',
31
+ '.svg': 'image/svg+xml',
32
+ '.mp4': 'video/mp4',
33
+ '.mov': 'video/quicktime',
34
+ '.webm': 'video/webm',
35
+ '.m4v': 'video/mp4',
36
+ '.txt': 'text/plain; charset=utf-8',
37
+ };
38
+
39
+ function resolveModule(spec) {
40
+ return fileURLToPath(import.meta.resolve(spec));
41
+ }
42
+
43
+ function safeJoin(base, rel) {
44
+ const p = path.resolve(base, '.' + path.sep + rel);
45
+ if (p !== base && !p.startsWith(base + path.sep)) return null;
46
+ return p;
47
+ }
48
+
49
+ // Project files the engine page may read: scenes.js and the modules it
50
+ // imports, images, fonts, audio and video. Never dotfiles such as .env, and
51
+ // no JSON, Markdown or text files, which can hold keys or private notes.
52
+ const PROJECT_FILES = /\.(m?js|png|jpe?g|webp|gif|svg|wav|mp3|mp4|mov|webm|m4v|woff2?|ttf|otf)$/i;
53
+
54
+ function allowedName(rel) {
55
+ const parts = rel.split(/[\\/]+/);
56
+ return !parts.some((x) => x.startsWith('.')) && PROJECT_FILES.test(rel);
57
+ }
58
+
59
+ function realInside(base, target) {
60
+ const root = fs.realpathSync(base);
61
+ return target === root || target.startsWith(root + path.sep);
62
+ }
63
+
64
+ // The rules apply to where a file really is: a symlink such as
65
+ // assets/logo.png -> ../../.env is followed and then refused.
66
+ export function projectFile(projectDir, rel) {
67
+ if (!allowedName(rel)) return null;
68
+ const file = safeJoin(projectDir, rel);
69
+ if (!file || !fs.existsSync(file)) return null;
70
+ const real = fs.realpathSync(file);
71
+ if (!realInside(projectDir, real)) return null;
72
+ const realRel = path.relative(fs.realpathSync(projectDir), real);
73
+ return allowedName(realRel) ? real : null;
74
+ }
75
+
76
+ function clipFile(projectDir, rel) {
77
+ if (!rel.startsWith('assets/') || !VIDEO_FILE.test(rel)) return null;
78
+ const file = projectFile(projectDir, rel);
79
+ const assets = path.join(fs.realpathSync(projectDir), 'assets');
80
+ if (!file || !VIDEO_FILE.test(file) || !file.startsWith(assets + path.sep) || !fs.statSync(file).isFile()) return null;
81
+ return file;
82
+ }
83
+
84
+ function clipCacheFile(projectDir, rel) {
85
+ const file = uploadFile(projectDir, rel);
86
+ if (!file) return null;
87
+ const realRel = path.relative(fs.realpathSync(projectDir), fs.realpathSync(path.dirname(file)));
88
+ return realRel.split(path.sep).some((p) => p.startsWith('.')) ? null : file;
89
+ }
90
+
91
+ const clipJobs = new Map();
92
+
93
+ async function cachedClip(projectDir, file, fps) {
94
+ const hash = crypto.createHash('sha256').update(JSON.stringify({ fps, width: 1920, version: 1 }));
95
+ for await (const chunk of fs.createReadStream(file)) hash.update(chunk);
96
+ const rel = `build/clips/${hash.digest('hex')}`;
97
+ const infoFile = clipCacheFile(projectDir, `${rel}/info.json`);
98
+ if (!infoFile) throw new Error('clip cache must stay in build/. Remove symlinks from build/clips/.');
99
+ const key = infoFile;
100
+ if (!clipJobs.has(key)) {
101
+ const job = (async () => {
102
+ if (fs.existsSync(infoFile)) return { rel, info: JSON.parse(fs.readFileSync(infoFile, 'utf8')) };
103
+ const temp = fs.mkdtempSync(path.join(path.dirname(infoFile), 'extract-'));
104
+ try {
105
+ const info = await extractClip(file, temp, fps);
106
+ for (const name of fs.readdirSync(temp)) {
107
+ const dest = clipCacheFile(projectDir, `${rel}/${name}`);
108
+ if (!dest) throw new Error('clip cache must stay in build/. Remove symlinks from build/clips/.');
109
+ fs.renameSync(path.join(temp, name), dest);
110
+ }
111
+ fs.writeFileSync(infoFile, JSON.stringify(info));
112
+ return { rel, info };
113
+ } finally {
114
+ fs.rmSync(temp, { recursive: true, force: true });
115
+ }
116
+ })();
117
+ clipJobs.set(key, job);
118
+ job.finally(() => clipJobs.delete(key)).catch(() => {});
119
+ }
120
+ return clipJobs.get(key);
121
+ }
122
+
123
+ // Uploads from the page may only land in build/ or out/: checked after the
124
+ // path is normalized (so "build/../scenes.js" is refused), and again on the
125
+ // real folder, and never onto a symlink.
126
+ function uploadFile(projectDir, rel) {
127
+ const dest = safeJoin(projectDir, rel);
128
+ if (!dest) return null;
129
+ const root = ['build', 'out'].find((d) => dest.startsWith(path.join(projectDir, d) + path.sep));
130
+ if (!root) return null;
131
+ const realProject = fs.realpathSync(projectDir);
132
+ const realRoot = path.join(realProject, root);
133
+ const underRoot = (p) => p === realRoot || p.startsWith(realRoot + path.sep);
134
+ // Check the folders that already exist before creating any.
135
+ let probe = path.dirname(dest);
136
+ while (!fs.existsSync(probe)) probe = path.dirname(probe);
137
+ const realProbe = fs.realpathSync(probe);
138
+ if (realProbe !== realProject && !underRoot(realProbe)) return null;
139
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
140
+ if (!underRoot(fs.realpathSync(path.dirname(dest)))) return null;
141
+ return isSymlink(dest) ? null : dest;
142
+ }
143
+
144
+ // lstat, not existsSync: a symlink to a missing file must be refused too.
145
+ function isSymlink(p) {
146
+ try {
147
+ return fs.lstatSync(p).isSymbolicLink();
148
+ } catch {
149
+ return false;
150
+ }
151
+ }
152
+
153
+ export async function startServer({ projectDir, getState, port = 0, log = () => {} }) {
154
+ const { config } = await getState();
155
+ await ensureFonts(config?.language, { log });
156
+ const fonts = new Map(['ja', 'zh'].flatMap(languageFonts).map(f => [`/language-fonts/${f.file}`, f.path]));
157
+ const roughPath = resolveModule('roughjs/bundled/rough.esm.js');
158
+ const clips = new Map();
159
+ const server = http.createServer(async (req, res) => {
160
+ try {
161
+ // Only answer requests addressed to this machine. A web page on another
162
+ // site that points its own domain at 127.0.0.1 (DNS rebinding) sends a
163
+ // different Host header and is turned away.
164
+ const port = server.address().port;
165
+ const hosts = [`127.0.0.1:${port}`, `localhost:${port}`];
166
+ if (!hosts.includes(req.headers.host)) return send(res, 403, 'forbidden host');
167
+ const origin = req.headers.origin;
168
+ if (origin && !hosts.some((h) => origin === `http://${h}`)) return send(res, 403, 'forbidden origin');
169
+ const url = new URL(req.url, 'http://x');
170
+ const p = decodeURIComponent(url.pathname);
171
+ if (p === '/__math') {
172
+ if (req.method !== 'GET') return send(res, 405, 'math only accepts GET');
173
+ const tex = url.searchParams.get('tex');
174
+ const style = url.searchParams.get('display') ?? '1';
175
+ if (tex === null || tex.length > MAX_TEX_LENGTH) return send(res, 400, `use a TeX string of at most ${MAX_TEX_LENGTH} characters`);
176
+ if (!['0', '1'].includes(style)) return send(res, 400, 'display must be 0 or 1');
177
+ const display = style === '1';
178
+ const file = uploadFile(projectDir, `build/math/${mathHash(tex, display)}.json`);
179
+ if (!file) return send(res, 400, 'math cache must stay in build/math/');
180
+ try {
181
+ const result = await typesetMath(tex, display, file);
182
+ return send(res, 200, JSON.stringify(result), TYPES['.json']);
183
+ } catch (e) {
184
+ return send(res, 400, JSON.stringify({ error: e.message }), TYPES['.json']);
185
+ }
186
+ }
187
+ if (req.method === 'PUT' && p === '/__upload') {
188
+ const rel = url.searchParams.get('path') || '';
189
+ const dest = uploadFile(projectDir, rel);
190
+ if (!dest) return send(res, 400, 'uploads go to build/ or out/');
191
+ const chunks = [];
192
+ for await (const c of req) chunks.push(c);
193
+ const body = Buffer.concat(chunks);
194
+ // Chunked upload (engine/upload.js): the pieces of one upload carry its
195
+ // random id and their byte offset, and are assembled in
196
+ // "<dest>.<id>.part" next to the target, which replaces the target only
197
+ // when the last piece has arrived. A piece at the wrong offset is
198
+ // refused, an interrupted upload never leaves a half-written file under
199
+ // the real name, and a new upload of the same file (offset 0) removes
200
+ // older partial uploads, so a stale or competing upload fails instead
201
+ // of mixing bytes into the result.
202
+ if (url.searchParams.has('offset')) {
203
+ const rawOffset = url.searchParams.get('offset');
204
+ const offset = Number(rawOffset);
205
+ if (!/^\d+$/.test(rawOffset) || !Number.isSafeInteger(offset)) return send(res, 400, 'offset must be a non-negative integer');
206
+ const id = url.searchParams.get('upload') || '';
207
+ if (!/^[0-9a-f]{16,64}$/.test(id)) return send(res, 400, 'upload must be a hexadecimal upload id');
208
+ const part = `${dest}.${id}.part`;
209
+ if (isSymlink(part)) return send(res, 400, 'uploads go to build/ or out/');
210
+ if (offset === 0) {
211
+ const stale = new RegExp(`^${path.basename(dest).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\.[0-9a-f]{16,64}\\.part$`);
212
+ for (const name of fs.readdirSync(path.dirname(dest))) {
213
+ if (stale.test(name)) fs.rmSync(path.join(path.dirname(dest), name), { force: true });
214
+ }
215
+ fs.writeFileSync(part, body);
216
+ } else {
217
+ const have = fs.existsSync(part) ? fs.statSync(part).size : null;
218
+ if (have !== offset) return send(res, 409, `upload piece out of order: expected offset ${have ?? 0}, got ${offset}`);
219
+ fs.appendFileSync(part, body);
220
+ }
221
+ if (url.searchParams.get('last') === '1') fs.renameSync(part, dest);
222
+ return send(res, 200, 'ok');
223
+ }
224
+ fs.writeFileSync(dest, body);
225
+ return send(res, 200, 'ok');
226
+ }
227
+ if (req.method !== 'GET' && req.method !== 'HEAD') return send(res, 405, 'method not allowed');
228
+ if (p === '/favicon.ico') return send(res, 204, '');
229
+ if (p === '/__state.json') {
230
+ const state = await getState();
231
+ return send(res, 200, JSON.stringify(state), TYPES['.json']);
232
+ }
233
+ if (['/__clip/info', '/__clip/frame', '/__clip/audio'].includes(p)) {
234
+ const file = clipFile(projectDir, url.searchParams.get('path') || '');
235
+ if (!file) return send(res, 404, 'clip not found. Put a video in assets/.');
236
+ const state = await getState();
237
+ const stat = fs.statSync(file);
238
+ const stamp = `${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}:${state.config.fps}`;
239
+ if (clips.get(file)?.stamp !== stamp) {
240
+ const job = cachedClip(projectDir, file, state.config.fps);
241
+ clips.set(file, { stamp, job });
242
+ job.catch(() => { if (clips.get(file)?.job === job) clips.delete(file); });
243
+ }
244
+ const { rel, info } = await clips.get(file).job;
245
+ if (p === '/__clip/info') return send(res, 200, JSON.stringify(info), TYPES['.json']);
246
+ let name = 'audio.wav';
247
+ if (p === '/__clip/frame') {
248
+ const raw = url.searchParams.get('frame') || '0';
249
+ if (!/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw))) return send(res, 400, 'frame must be a non-negative integer');
250
+ name = `${String(Math.min(Number(raw), info.frames - 1)).padStart(8, '0')}.jpg`;
251
+ } else if (!info.hasAudio) return send(res, 404, 'this clip has no sound');
252
+ const cached = clipCacheFile(projectDir, `${rel}/${name}`);
253
+ if (!cached || !fs.existsSync(cached) || !fs.statSync(cached).isFile()) return send(res, 404, 'clip frame or sound not found');
254
+ res.writeHead(200, { 'Content-Type': TYPES[path.extname(name)], 'Cache-Control': 'no-store' });
255
+ if (req.method === 'HEAD') return res.end();
256
+ fs.createReadStream(cached).pipe(res);
257
+ return;
258
+ }
259
+ let file = null;
260
+ if (p === '/' || p === '/studio.html') file = path.join(ROOT, 'engine', 'studio.html');
261
+ else if (p === '/frame.html') file = path.join(ROOT, 'engine', 'frame.html');
262
+ else if (fonts.has(p)) file = fonts.get(p);
263
+ else if (p === '/vendor/rough.js') file = roughPath;
264
+ else if (p.startsWith('/engine/')) file = safeJoin(path.join(ROOT, 'engine'), p.slice(8));
265
+ else if (p.startsWith('/fonts/')) file = safeJoin(path.join(ROOT, 'fonts'), p.slice(7));
266
+ else if (p.startsWith('/project/')) file = projectFile(projectDir, p.slice(9));
267
+ if (!file || !fs.existsSync(file) || !fs.statSync(file).isFile()) return send(res, 404, `not found: ${p}`);
268
+ const type = TYPES[path.extname(file).toLowerCase()] || 'application/octet-stream';
269
+ res.writeHead(200, { 'Content-Type': type, 'Cache-Control': 'no-store' });
270
+ if (req.method === 'HEAD') return res.end();
271
+ fs.createReadStream(file).pipe(res);
272
+ } catch (e) {
273
+ send(res, 500, String(e && e.stack || e));
274
+ }
275
+ });
276
+ return new Promise((resolve, reject) => {
277
+ server.once('error', reject);
278
+ server.listen(port, '127.0.0.1', () => {
279
+ const { port: actual } = server.address();
280
+ resolve({ url: `http://127.0.0.1:${actual}`, port: actual, close: () => new Promise((r) => { server.closeAllConnections(); server.close(() => r()); }) });
281
+ });
282
+ });
283
+ }
284
+
285
+ function send(res, code, body, type = 'text/plain; charset=utf-8') {
286
+ res.writeHead(code, { 'Content-Type': type, 'Cache-Control': 'no-store' });
287
+ res.end(body);
288
+ }
@@ -0,0 +1,78 @@
1
+ // Subtitle cues use the shown words and their times from the voice timeline.
2
+ import { clingsToPrevious } from '../engine/captions.js';
3
+
4
+ const sentenceEnd = /[.!?…।]["'’”)\]]*$/;
5
+ const punctuation = /[,;:.!?…।]["'’”)\]]*$/;
6
+
7
+ function lines(words, language = 'en') {
8
+ const cjk = ['ja', 'zh'].includes(language);
9
+ const clings = clingsToPrevious(language);
10
+ const limit = cjk ? 18 : 42;
11
+ const separator = cjk ? '' : ' ';
12
+ const text = words.map((w) => w.text).join(separator);
13
+ if (text.length <= limit) return text;
14
+ let best = null;
15
+ for (let i = 1; i < words.length; i++) {
16
+ const a = words.slice(0, i).map((w) => w.text).join(separator);
17
+ const b = words.slice(i).map((w) => w.text).join(separator);
18
+ if (a.length > limit || b.length > limit) continue;
19
+ // Break after punctuation, unless that leaves a word or two alone on a line.
20
+ const atPunctuation = (cjk ? /[,;:.!?…।。!?、,;:]["'’”)\]」』)]*$/ : punctuation).test(words[i - 1].text) && Math.min(a.length, b.length) >= (cjk ? 5 : 12);
21
+ const glued = !atPunctuation && clings(words[i].text, words[i - 1].text) ? 40 : 0;
22
+ const score = (atPunctuation ? 30 : 0) - Math.abs(a.length - b.length) - glued;
23
+ if (!best || score > best.score) best = { score, text: `${a}\n${b}` };
24
+ }
25
+ return best?.text ?? null;
26
+ }
27
+
28
+ export function subtitleCues(timeline, { from = 0, to = Infinity } = {}) {
29
+ const language = timeline.language || 'en';
30
+ const cjk = ['ja', 'zh'].includes(language);
31
+ const limit = cjk ? 18 : 42;
32
+ const endSentence = cjk ? /[.!?…।。!?]["'’”)\]」』)]*$/ : sentenceEnd;
33
+ const atPunctuation = cjk ? /[,;:.!?…।。!?、,;:]["'’”)\]」』)]*$/ : punctuation;
34
+ const clings = clingsToPrevious(language);
35
+ const cues = [];
36
+ for (const scene of timeline.scenes) {
37
+ const words = scene.words || [];
38
+ let i = 0;
39
+ while (i < words.length) {
40
+ if (words[i].text.length > limit) throw new Error(`subtitle word "${words[i].text}" is longer than ${limit} characters. Shorten its shown text in script.md.`);
41
+ let j = i + 1;
42
+ while (j < words.length) {
43
+ if (endSentence.test(words[j - 1].text) || words[j].start - words[j - 1].end > 0.6 + 1e-9) break;
44
+ if (words[j].end + 0.25 - words[i].start > 6 || lines(words.slice(i, j + 1), language) === null) {
45
+ let k = j - 1;
46
+ while (k > i && !atPunctuation.test(words[k - 1].text)) k--;
47
+ if (k > i) j = k;
48
+ // Without punctuation, start the next cue at a word of its own.
49
+ else while (j - 1 > i && clings(words[j].text, words[j - 1].text)) j--;
50
+ break;
51
+ }
52
+ j++;
53
+ }
54
+ const start = scene.start + words[i].start;
55
+ const end = Math.min(scene.start + words[j - 1].end + 0.25, start + 6, scene.start + (scene.dur ?? Infinity));
56
+ cues.push({ start, end, text: lines(words.slice(i, j), language) });
57
+ i = j;
58
+ }
59
+ }
60
+ for (let i = 0; i < cues.length - 1; i++) cues[i].end = Math.min(cues[i].end, cues[i + 1].start);
61
+ return cues.filter((c) => c.end > from && c.start < to).map((c) => ({
62
+ ...c, start: Math.max(c.start, from) - from, end: Math.min(c.end, to) - from,
63
+ }));
64
+ }
65
+
66
+ function timestamp(seconds, separator) {
67
+ const ms = Math.max(0, Math.round(seconds * 1000));
68
+ const pad = (n, width = 2) => String(n).padStart(width, '0');
69
+ return `${pad(Math.floor(ms / 3600000))}:${pad(Math.floor(ms / 60000) % 60)}:${pad(Math.floor(ms / 1000) % 60)}${separator}${pad(ms % 1000, 3)}`;
70
+ }
71
+
72
+ export function toSrt(cues) {
73
+ return cues.map((c, i) => `${i + 1}\n${timestamp(c.start, ',')} --> ${timestamp(c.end, ',')}\n${c.text}\n\n`).join('');
74
+ }
75
+
76
+ export function toVtt(cues) {
77
+ return 'WEBVTT\n\n' + cues.map((c) => `${timestamp(c.start, '.')} --> ${timestamp(c.end, '.')}\n${c.text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}\n\n`).join('');
78
+ }
@@ -0,0 +1,55 @@
1
+ // Lays scenes end to end. A scene lasts for its lead-in, its narration and a
2
+ // short hold; scenes without narration last `min` seconds (default 3).
3
+ // `pace` shortens every lead-in, hold and transition (the voice is already
4
+ // faster). All times are snapped to the frame grid.
5
+
6
+ export const TRANSITION_SECONDS = 0.7;
7
+
8
+ export function buildTimeline(project, voices) {
9
+ const { config, script } = project;
10
+ const fps = config.fps;
11
+ const pace = config.pace || 1;
12
+ const snap = (t) => Math.round(t * fps) / fps;
13
+ const scenes = [];
14
+ const voiceSpans = [];
15
+ let t = 0;
16
+ script.scenes.forEach((scene, index) => {
17
+ const v = voices[scene.id] || { duration: 0, words: [], marks: {}, chunks: [] };
18
+ const a = scene.attrs;
19
+ const lead = v.duration ? (a.lead ?? config.lead) / pace : 0;
20
+ const isLast = index === script.scenes.length - 1;
21
+ const hold = ((a.hold ?? config.hold) + (isLast ? config.end : 0)) / pace;
22
+ let dur = v.duration ? lead + v.duration + hold : ((a.min ?? 3) + (isLast ? config.end : 0)) / pace;
23
+ if (a.min) dur = Math.max(dur, a.min / pace);
24
+ dur = Math.max(snap(dur), 1);
25
+ const start = snap(t);
26
+ const transition = index === 0 ? 'none' : (a.transition || config.transition);
27
+ scenes.push({
28
+ id: scene.id,
29
+ index,
30
+ start,
31
+ dur,
32
+ lead,
33
+ text: scene.text,
34
+ transition,
35
+ voice: v.duration ? { url: `build/voice/${scene.id}.wav`, start: start + lead, dur: v.duration } : null,
36
+ words: v.words.map((w) => ({ text: w.text, start: lead + w.start, end: lead + w.end })),
37
+ marks: Object.fromEntries(Object.entries(v.marks || {}).map(([k, m]) => [k, lead + m])),
38
+ attrs: a,
39
+ });
40
+ for (const c of v.chunks || []) voiceSpans.push({ start: start + lead + c.start, end: start + lead + c.end });
41
+ t = start + dur;
42
+ });
43
+ return {
44
+ fps,
45
+ ...(['ja', 'zh'].includes(config.language) ? { language: config.language } : {}),
46
+ width: config.width,
47
+ height: config.height,
48
+ duration: snap(t),
49
+ frames: Math.round(snap(t) * fps),
50
+ transitionSeconds: TRANSITION_SECONDS / pace,
51
+ pace,
52
+ scenes,
53
+ voiceSpans,
54
+ };
55
+ }
@@ -0,0 +1,240 @@
1
+ // Turns each scene's narration into a WAV file plus word timings.
2
+ // Results are cached per scene in build/voice/<scene>.json and only
3
+ // regenerated when the words, markers, voice, speed or pacing change.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import { speechChunks, resolveMarks, normWord } from './script.js';
8
+ import { alignWords, readAlike } from './align.js';
9
+ import { loadTTS, transcribeWords, TTS_MODEL, TTS_SAMPLE_RATE, ttsDtype, asrModel } from './models.js';
10
+ import { phonemize, generateSpeech } from './phonemes.js';
11
+ import { writeWav, readWav, resample, trimSilence } from './wav.js';
12
+ import { elevenSpeech } from './elevenlabs.js';
13
+ import { recordingFiles, decodeRecording, saveRecording, recordingCuts } from './recordings.js';
14
+
15
+ const PIPELINE = 7;
16
+
17
+ export function sceneHash(scene, chunks, config, recording = null) {
18
+ return crypto
19
+ .createHash('sha256')
20
+ .update(JSON.stringify({
21
+ PIPELINE,
22
+ TTS_MODEL,
23
+ ASR_MODEL: asrModel(config.language),
24
+ dtype: ttsDtype(),
25
+ voice: config.voice,
26
+ speed: config.speed * config.pace,
27
+ chunks: recording ? scene.spoken : chunks.map((c) => [c.gapBefore, c.text]),
28
+ // Markers and the shown text of each word are saved with the timings,
29
+ // so moving a [#marker] or changing {shown|spoken} makes the scene again.
30
+ layout: (recording ? scene.units.filter((u) => u.type !== 'pause') : scene.units).map((u) => (u.type === 'mark' ? `#${u.name}` : u.type === 'word' ? u.display : '')).join('|'),
31
+ // Added last and only for recordings, so Kokoro scenes keep their cache.
32
+ ...(recording ? { recording } : {}),
33
+ ...(config.language && config.language !== 'en' ? { language: config.language } : {}),
34
+ }))
35
+ .digest('hex')
36
+ .slice(0, 16);
37
+ }
38
+
39
+ export function voicePaths(project, id) {
40
+ return { wav: path.join(project.paths.voice, `${id}.wav`), json: path.join(project.paths.voice, `${id}.json`) };
41
+ }
42
+
43
+ export function readVoice(project, id) {
44
+ const p = voicePaths(project, id);
45
+ if (!fs.existsSync(p.json)) return null;
46
+ try {
47
+ return JSON.parse(fs.readFileSync(p.json, 'utf8'));
48
+ } catch {
49
+ return null;
50
+ }
51
+ }
52
+
53
+ // Returns { [sceneId]: voiceInfo } and generates whatever is missing or stale.
54
+ export async function synthesize(project, { force = false, log = () => {}, only = null } = {}) {
55
+ fs.mkdirSync(project.paths.voice, { recursive: true });
56
+ const { config } = project;
57
+ const provider = config.voice.provider || 'kokoro';
58
+ const recordings = provider === 'recording' ? recordingFiles(project) : null;
59
+ const result = {};
60
+ const todo = [];
61
+ for (const scene of project.script.scenes) {
62
+ const chunks = speechChunks(scene.units, { sentenceGap: config.sentenceGap, paragraphGap: config.paragraphGap, pace: config.pace, language: config.language });
63
+ const recording = recordings?.files[scene.id];
64
+ const hash = sceneHash(scene, chunks, config, recording ? {
65
+ content: recording.hash,
66
+ scenes: recordings.folder ? null : project.script.scenes.map((s) => s.spoken),
67
+ } : null);
68
+ const cached = readVoice(project, scene.id);
69
+ const hasAudio = !chunks.length || fs.existsSync(voicePaths(project, scene.id).wav);
70
+ if (!force && cached && cached.hash === hash && hasAudio) {
71
+ result[scene.id] = cached;
72
+ } else if (only && !only.includes(scene.id) && cached) {
73
+ result[scene.id] = cached;
74
+ } else {
75
+ todo.push({ scene, chunks, hash });
76
+ }
77
+ }
78
+ if (!todo.length) return result;
79
+
80
+ const needsSpeech = todo.some((t) => t.chunks.length);
81
+ const tts = needsSpeech && provider === 'kokoro' ? await loadTTS({ log }) : null;
82
+ const wanted = config.speed * config.pace;
83
+ let take = null;
84
+ let cuts = [];
85
+ let heardTake = null;
86
+ if (needsSpeech && recordings && !recordings.folder) {
87
+ log('transcribing the recording and finding scene boundaries');
88
+ take = await decodeRecording(Object.values(recordings.files)[0].file, project.paths.build, wanted);
89
+ heardTake = await transcribeWords(resample(take.samples, take.sampleRate, 16000), { log, language: config.language });
90
+ cuts = recordingCuts(project.script.scenes, heardTake.words, take.samples.length / take.sampleRate, config.language);
91
+ }
92
+ for (const { scene, chunks, hash } of todo) {
93
+ const t0 = Date.now();
94
+ const info = recordings && chunks.length
95
+ ? await recordingScene(project, scene, hash, recordings.files[scene.id], take, cuts.find((c) => c.scene.id === scene.id), heardTake, log)
96
+ : await synthesizeScene(project, scene, chunks, hash, tts, log);
97
+ result[scene.id] = info;
98
+ if (chunks.length) {
99
+ const warn = info.matchRate < 0.85 ? (recordings
100
+ ? `, recording does not match script.md here (${Math.round(info.matchRate * 100)}% of words confirmed). Make script.md say what was actually said.`
101
+ : `, check pronunciation (${Math.round(info.matchRate * 100)}% of words confirmed)`) : '';
102
+ log(`voice ${scene.id}: ${info.duration.toFixed(1)}s in ${((Date.now() - t0) / 1000).toFixed(1)}s${warn}`);
103
+ }
104
+ }
105
+ return result;
106
+ }
107
+
108
+ async function synthesizeScene(project, scene, chunks, hash, tts, log) {
109
+ const { config } = project;
110
+ const files = voicePaths(project, scene.id);
111
+ if (!chunks.length) {
112
+ const info = { hash, id: scene.id, duration: 0, words: [], marks: resolveMarks(scene.units, []), chunks: [], transcript: '', matchRate: 1, unmatched: [] };
113
+ if (fs.existsSync(files.wav)) fs.rmSync(files.wav);
114
+ fs.writeFileSync(files.json, JSON.stringify(info, null, 2));
115
+ return info;
116
+ }
117
+ const sr = TTS_SAMPLE_RATE;
118
+ const pieces = [];
119
+ let cursor = 0;
120
+ const chunkInfo = [];
121
+ const wordTimes = [];
122
+ const transcripts = [];
123
+ const unmatched = [];
124
+ let matchedTokens = 0;
125
+ let totalTokens = 0;
126
+
127
+ const phonemes = config.voice.provider !== 'elevenlabs' && config.language !== 'en'
128
+ ? await phonemize(chunks.map(c => c.text), config.language) : null;
129
+ for (let ci = 0; ci < chunks.length; ci++) {
130
+ const chunk = chunks[ci];
131
+ const gap = ci === 0 ? 0 : chunk.gapBefore;
132
+ if (gap > 0) {
133
+ pieces.push(new Float32Array(Math.round(gap * sr)));
134
+ cursor += Math.round(gap * sr);
135
+ }
136
+ const audio = config.voice.provider === 'elevenlabs'
137
+ ? await elevenSpeech(project, scene.id, chunk.text, { previous: chunks[ci - 1]?.text, next: chunks[ci + 1]?.text })
138
+ : await generateSpeech(tts, chunk.text, { language: config.language, voice: config.voice, speed: config.speed * config.pace, phonemes: phonemes?.[ci] });
139
+ const samples = trimSilence(audio.audio, audio.sampling_rate || sr);
140
+ const start = cursor / sr;
141
+ const dur = samples.length / sr;
142
+ pieces.push(samples);
143
+ cursor += samples.length;
144
+
145
+ const heard = await transcribeWords(resample(samples, sr, 16000), { log, language: config.language });
146
+ transcripts.push(heard.text);
147
+ const alike = await readAlike(chunk.words, heard.words, config.language);
148
+ const aligned = alignWords(alike.words, alike.heard, dur, config.language);
149
+ chunk.words.forEach((w, k) => {
150
+ const a = aligned.words[k];
151
+ wordTimes[w.unitIndex] = { start: start + a.start, end: start + a.end, matched: a.matched };
152
+ if (!a.matched) unmatched.push(w.display);
153
+ });
154
+ const tokens = chunk.words.reduce((n, w) => n + (['ja', 'zh'].includes(config.language) ? Array.from(normWord(w.spoken).normalize('NFC')).length : w.spoken.split(/\s+/).length), 0);
155
+ totalTokens += tokens;
156
+ matchedTokens += aligned.matchRate * tokens;
157
+ chunkInfo.push({ start, end: start + dur, text: chunk.text });
158
+ }
159
+
160
+ const total = new Float32Array(cursor);
161
+ let off = 0;
162
+ for (const p of pieces) {
163
+ total.set(p, off);
164
+ off += p.length;
165
+ }
166
+ writeWav(files.wav, total, sr);
167
+
168
+ const words = [];
169
+ scene.units.forEach((u, i) => {
170
+ if (u.type !== 'word' || !wordTimes[i]) return;
171
+ words.push({ text: u.display, spoken: u.spoken, start: round(wordTimes[i].start), end: round(wordTimes[i].end), matched: wordTimes[i].matched });
172
+ });
173
+ const info = {
174
+ hash,
175
+ id: scene.id,
176
+ duration: round(cursor / sr),
177
+ words,
178
+ marks: Object.fromEntries(Object.entries(resolveMarks(scene.units, wordTimes)).map(([k, v]) => [k, round(v)])),
179
+ chunks: chunkInfo.map((c) => ({ ...c, start: round(c.start), end: round(c.end) })),
180
+ transcript: transcripts.join(' '),
181
+ matchRate: totalTokens ? Math.round((matchedTokens / totalTokens) * 1000) / 1000 : 1,
182
+ unmatched,
183
+ };
184
+ fs.writeFileSync(files.json, JSON.stringify(info, null, 2));
185
+ return info;
186
+ }
187
+
188
+ async function recordingScene(project, scene, hash, source, take, cut, heardTake, log) {
189
+ const { config } = project;
190
+ const audio = take || await decodeRecording(source.file, project.paths.build, project.config.speed * project.config.pace);
191
+ const sr = audio.sampleRate;
192
+ let from = cut ? Math.floor(cut.start * sr) : 0;
193
+ let to = cut ? Math.ceil(cut.end * sr) : audio.samples.length;
194
+ let samples = audio.samples.subarray(from, to);
195
+ if (cut) {
196
+ // Whisper can include the silence between scenes in a word's timestamp.
197
+ const trimmed = trimSilence(samples, sr, { keep: 0.15 });
198
+ if (trimmed.length) {
199
+ from += (trimmed.byteOffset - samples.byteOffset) / 4;
200
+ samples = trimmed;
201
+ to = from + samples.length;
202
+ }
203
+ }
204
+ const duration = samples.length / sr;
205
+ const local = (w) => {
206
+ const start = Math.max(0, Math.min(duration, w.start - from / sr));
207
+ return { ...w, start, end: Math.min(duration, Math.max(start + 0.05, w.end - from / sr)) };
208
+ };
209
+ const heard = heardTake ? {
210
+ words: heardTake.words.filter((w) => w.start >= cut.start && w.start < cut.end).map(local),
211
+ } : await transcribeWords(resample(samples, sr, 16000), { log, language: config.language });
212
+ const units = scene.units.filter((u) => u.type === 'word');
213
+ const alike = await readAlike(units, heard.words, config.language);
214
+ const aligned = alignWords(alike.words, alike.heard, duration, config.language);
215
+ const times = cut ? cut.words.map(local) : aligned.words;
216
+ const wordTimes = [];
217
+ let wi = 0;
218
+ scene.units.forEach((u, i) => { if (u.type === 'word') wordTimes[i] = times[wi++]; });
219
+ const files = voicePaths(project, scene.id);
220
+ await saveRecording(files.wav, samples, sr);
221
+ const info = {
222
+ hash, id: scene.id, duration: round(duration),
223
+ words: units.map((u, i) => ({ text: u.display, spoken: u.spoken, start: round(times[i].start), end: round(times[i].end), matched: aligned.words[i].matched })),
224
+ marks: Object.fromEntries(Object.entries(resolveMarks(scene.units, wordTimes)).map(([k, v]) => [k, round(v)])),
225
+ chunks: [{ start: 0, end: round(duration), text: scene.spoken }],
226
+ transcript: heard.words.map((w) => w.text).join(' '),
227
+ matchRate: round(aligned.matchRate), unmatched: units.filter((u, i) => !aligned.words[i].matched).map((u) => u.display),
228
+ };
229
+ fs.writeFileSync(files.json, JSON.stringify(info, null, 2));
230
+ return info;
231
+ }
232
+
233
+ function round(v) {
234
+ return Math.round(v * 1000) / 1000;
235
+ }
236
+
237
+ export function voiceSamples(project, id) {
238
+ const p = voicePaths(project, id).wav;
239
+ return fs.existsSync(p) ? readWav(p) : null;
240
+ }