@biunow/agent-biutalk 0.0.0-stage → 1.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.
- package/bin/server.js +355 -0
- package/engine/AGENTS.md +1414 -0
- package/engine/CLAUDE.md +1 -0
- package/engine/LICENSE +21 -0
- package/engine/README.md +216 -0
- package/engine/bin/explainroo.js +19 -0
- package/engine/dev/audio-lab.mjs +268 -0
- package/engine/docs/media/contact-sheet.jpg +0 -0
- package/engine/docs/media/dns-poster.jpg +0 -0
- package/engine/docs/media/intro-poster.jpg +0 -0
- package/engine/docs/media/logo-dark.png +0 -0
- package/engine/docs/media/logo-light.png +0 -0
- package/engine/docs/media/looks-dark.webp +0 -0
- package/engine/docs/media/looks-light.webp +0 -0
- package/engine/docs/media/product-demo.webp +0 -0
- package/engine/docs/media/rebase-poster.jpg +0 -0
- package/engine/docs/media/sizes-dark.webp +0 -0
- package/engine/docs/media/sizes-light.webp +0 -0
- package/engine/engine/audio/dsp.js +69 -0
- package/engine/engine/audio/instruments.js +147 -0
- package/engine/engine/audio/music.js +576 -0
- package/engine/engine/audio/pcm.js +93 -0
- package/engine/engine/audio/rng.js +40 -0
- package/engine/engine/audio/sfx.js +287 -0
- package/engine/engine/audio/soundtrack.js +201 -0
- package/engine/engine/audio/synth.js +721 -0
- package/engine/engine/audio/theory.js +105 -0
- package/engine/engine/audio/wav.js +47 -0
- package/engine/engine/captions.js +131 -0
- package/engine/engine/clips.js +107 -0
- package/engine/engine/code.js +179 -0
- package/engine/engine/director.js +475 -0
- package/engine/engine/frame.html +135 -0
- package/engine/engine/icons/LICENSE-lucide.txt +43 -0
- package/engine/engine/icons/lucide-tags.json +1 -0
- package/engine/engine/icons/lucide.json +1 -0
- package/engine/engine/layout.js +69 -0
- package/engine/engine/pathdata.js +234 -0
- package/engine/engine/pen.js +240 -0
- package/engine/engine/player.html +67 -0
- package/engine/engine/player.js +219 -0
- package/engine/engine/readability.js +9 -0
- package/engine/engine/runtime.js +690 -0
- package/engine/engine/stage.js +2247 -0
- package/engine/engine/studio.html +216 -0
- package/engine/engine/text.js +81 -0
- package/engine/engine/themes.js +360 -0
- package/engine/engine/transitions.js +161 -0
- package/engine/engine/ui.js +1042 -0
- package/engine/engine/upload.js +32 -0
- package/engine/engine/util.js +204 -0
- package/engine/examples/callbacks-to-async-await/code-versions.js +34 -0
- package/engine/examples/callbacks-to-async-await/scenes.js +106 -0
- package/engine/examples/callbacks-to-async-await/script.md +22 -0
- package/engine/examples/callbacks-to-async-await/video.json +16 -0
- package/engine/examples/circle-area/scenes.js +228 -0
- package/engine/examples/circle-area/script.md +37 -0
- package/engine/examples/circle-area/video.json +14 -0
- package/engine/examples/explainroo-intro/scenes.js +133 -0
- package/engine/examples/explainroo-intro/script.md +27 -0
- package/engine/examples/explainroo-intro/video.json +8 -0
- package/engine/examples/how-dns-works/scenes.js +130 -0
- package/engine/examples/how-dns-works/script.md +28 -0
- package/engine/examples/how-dns-works/video.json +8 -0
- package/engine/examples/leap-years/scenes.js +156 -0
- package/engine/examples/leap-years/script.md +25 -0
- package/engine/examples/leap-years/video.json +16 -0
- package/engine/examples/leap-years-ja/scenes.js +194 -0
- package/engine/examples/leap-years-ja/script.md +32 -0
- package/engine/examples/leap-years-ja/video.json +17 -0
- package/engine/examples/merge-vs-rebase/scenes.js +129 -0
- package/engine/examples/merge-vs-rebase/script.md +22 -0
- package/engine/examples/merge-vs-rebase/video.json +8 -0
- package/engine/examples/password-storage-zh/scenes.js +185 -0
- package/engine/examples/password-storage-zh/script.md +25 -0
- package/engine/examples/password-storage-zh/video.json +19 -0
- package/engine/examples/sqlite-demo/README.md +19 -0
- package/engine/examples/sqlite-demo/scenes.js +423 -0
- package/engine/examples/sqlite-demo/script.md +35 -0
- package/engine/examples/sqlite-demo/video.json +17 -0
- package/engine/examples/unspar-demo/assets/fonts/Figtree-400.woff2 +0 -0
- package/engine/examples/unspar-demo/assets/fonts/Figtree-500.woff2 +0 -0
- package/engine/examples/unspar-demo/assets/fonts/Figtree-600.woff2 +0 -0
- package/engine/examples/unspar-demo/assets/fonts/Figtree-700.woff2 +0 -0
- package/engine/examples/unspar-demo/assets/fonts/Figtree-OFL.txt +93 -0
- package/engine/examples/unspar-demo/assets/unspar-logo.svg +23 -0
- package/engine/examples/unspar-demo/scenes.js +367 -0
- package/engine/examples/unspar-demo/script.md +25 -0
- package/engine/examples/unspar-demo/video.json +21 -0
- package/engine/examples/why-is-the-sky-blue-es/scenes.js +160 -0
- package/engine/examples/why-is-the-sky-blue-es/script.md +22 -0
- package/engine/examples/why-is-the-sky-blue-es/video.json +15 -0
- package/engine/fonts/ArchitectsDaughter-400-latin-ext.woff2 +0 -0
- package/engine/fonts/ArchitectsDaughter-400-latin.woff2 +0 -0
- package/engine/fonts/CabinSketch-400-latin.woff2 +0 -0
- package/engine/fonts/CabinSketch-700-latin.woff2 +0 -0
- package/engine/fonts/InstrumentSerif-400-italic-latin-ext.woff2 +0 -0
- package/engine/fonts/InstrumentSerif-400-italic-latin.woff2 +0 -0
- package/engine/fonts/InstrumentSerif-400-normal-latin-ext.woff2 +0 -0
- package/engine/fonts/InstrumentSerif-400-normal-latin.woff2 +0 -0
- package/engine/fonts/Inter-400-latin-ext.woff2 +0 -0
- package/engine/fonts/Inter-400-latin.woff2 +0 -0
- package/engine/fonts/JetBrainsMono-400-latin-ext.woff2 +0 -0
- package/engine/fonts/JetBrainsMono-400-latin.woff2 +0 -0
- package/engine/fonts/Kalam-400-latin-ext.woff2 +0 -0
- package/engine/fonts/Kalam-400-latin.woff2 +0 -0
- package/engine/fonts/Kalam-700-latin-ext.woff2 +0 -0
- package/engine/fonts/Kalam-700-latin.woff2 +0 -0
- package/engine/fonts/NotoSansDevanagari-400.ttf +0 -0
- package/engine/fonts/NotoSansDevanagari-700.ttf +0 -0
- package/engine/fonts/PatrickHand-400-latin-ext.woff2 +0 -0
- package/engine/fonts/PatrickHand-400-latin.woff2 +0 -0
- package/engine/fonts/PlusJakartaSans-600-latin-ext.woff2 +0 -0
- package/engine/fonts/PlusJakartaSans-600-latin.woff2 +0 -0
- package/engine/fonts/SpaceGrotesk-500-latin-ext.woff2 +0 -0
- package/engine/fonts/SpaceGrotesk-500-latin.woff2 +0 -0
- package/engine/fonts/fonts.json +216 -0
- package/engine/fonts/licenses/ArchitectsDaughter-OFL.txt +93 -0
- package/engine/fonts/licenses/CabinSketch-OFL.txt +93 -0
- package/engine/fonts/licenses/InstrumentSerif-OFL.txt +93 -0
- package/engine/fonts/licenses/Inter-OFL.txt +93 -0
- package/engine/fonts/licenses/JetBrainsMono-OFL.txt +93 -0
- package/engine/fonts/licenses/Kalam-OFL.txt +93 -0
- package/engine/fonts/licenses/NotoSansDevanagari-OFL.txt +118 -0
- package/engine/fonts/licenses/PatrickHand-OFL.txt +93 -0
- package/engine/fonts/licenses/PlusJakartaSans-OFL.txt +93 -0
- package/engine/fonts/licenses/SpaceGrotesk-OFL.txt +93 -0
- package/engine/package-lock.json +1201 -0
- package/engine/package.json +67 -0
- package/engine/scripts/build-icons.mjs +74 -0
- package/engine/scripts/fetch-fonts.mjs +68 -0
- package/engine/skills/explainroo/SKILL.md +51 -0
- package/engine/src/align.js +357 -0
- package/engine/src/browser.js +121 -0
- package/engine/src/capture.js +315 -0
- package/engine/src/chapters.js +32 -0
- package/engine/src/cli.js +421 -0
- package/engine/src/clips.js +19 -0
- package/engine/src/elevenlabs.js +90 -0
- package/engine/src/env.js +16 -0
- package/engine/src/export.js +187 -0
- package/engine/src/ffmpeg.js +103 -0
- package/engine/src/fonts.js +86 -0
- package/engine/src/g2p.py +76 -0
- package/engine/src/images.js +151 -0
- package/engine/src/licenses/misaki-Apache-2.0.txt +201 -0
- package/engine/src/math.js +83 -0
- package/engine/src/models.js +161 -0
- package/engine/src/phonemes.js +162 -0
- package/engine/src/pipeline.js +63 -0
- package/engine/src/project.js +331 -0
- package/engine/src/qa.js +186 -0
- package/engine/src/recordings.js +89 -0
- package/engine/src/render.js +156 -0
- package/engine/src/script.js +266 -0
- package/engine/src/server.js +288 -0
- package/engine/src/subtitles.js +78 -0
- package/engine/src/timeline.js +55 -0
- package/engine/src/voice.js +240 -0
- package/engine/src/wav.js +98 -0
- package/engine/templates/starter/scenes.js +31 -0
- package/engine/templates/starter/script.md +14 -0
- package/engine/test/align.test.js +108 -0
- package/engine/test/brand.test.js +41 -0
- package/engine/test/browser.test.js +89 -0
- package/engine/test/camera-browser.test.js +225 -0
- package/engine/test/caption-phrases.test.js +35 -0
- package/engine/test/capture-browser.test.js +90 -0
- package/engine/test/capture-fixture.js +46 -0
- package/engine/test/capture.test.js +62 -0
- package/engine/test/chapters.test.js +41 -0
- package/engine/test/cjk-browser.test.js +101 -0
- package/engine/test/cjk.test.js +232 -0
- package/engine/test/cli-exit.test.js +25 -0
- package/engine/test/cli.test.js +116 -0
- package/engine/test/clips-browser.test.js +125 -0
- package/engine/test/clips.test.js +67 -0
- package/engine/test/code-morph-browser.test.js +99 -0
- package/engine/test/code-morph.test.js +110 -0
- package/engine/test/contrast-browser.test.js +63 -0
- package/engine/test/contrast.test.js +80 -0
- package/engine/test/director.test.js +316 -0
- package/engine/test/engine-pure.test.js +29 -0
- package/engine/test/export-browser.test.js +224 -0
- package/engine/test/export.test.js +96 -0
- package/engine/test/fixtures/capture.html +55 -0
- package/engine/test/formats-pace.test.js +104 -0
- package/engine/test/languages-browser.test.js +78 -0
- package/engine/test/languages.test.js +140 -0
- package/engine/test/looks-browser.test.js +109 -0
- package/engine/test/looks-preview.test.js +57 -0
- package/engine/test/looks.test.js +130 -0
- package/engine/test/math-browser.test.js +114 -0
- package/engine/test/math.test.js +54 -0
- package/engine/test/multi-size-browser.test.js +133 -0
- package/engine/test/multi-size.test.js +116 -0
- package/engine/test/phonemes.test.js +92 -0
- package/engine/test/readability-browser.test.js +36 -0
- package/engine/test/readability.test.js +20 -0
- package/engine/test/render-options.test.js +52 -0
- package/engine/test/script.test.js +67 -0
- package/engine/test/server.test.js +256 -0
- package/engine/test/stills-browser.test.js +70 -0
- package/engine/test/subtitles.test.js +83 -0
- package/engine/test/timeline.test.js +31 -0
- package/engine/test/transparent-browser.test.js +123 -0
- package/engine/test/ui-kit.test.js +96 -0
- package/engine/test/upload-browser.test.js +55 -0
- package/engine/test/voice-providers.test.js +338 -0
- package/lib/host.mjs +480 -0
- package/manifest.json +54 -0
- package/package.json +8 -4
- package/skills/biutalk/SKILL.md +21 -0
- package/studio/app.js +209 -0
- package/studio/assert-panel-permit.mjs +67 -0
- package/studio/composer.css +354 -0
- package/studio/composer.js +169 -0
- package/studio/index.html +82 -0
- package/studio/looks/blueprint.svg +21 -0
- package/studio/looks/chalk.svg +15 -0
- package/studio/looks/clean.svg +20 -0
- package/studio/looks/editorial.svg +18 -0
- package/studio/looks/midnight.svg +17 -0
- package/studio/looks/paper.svg +11 -0
- package/studio/select-menu.js +268 -0
- package/studio/styles.css +4 -0
- package/README.md +0 -3
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
// explainroo command line.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { loadProject, ProjectError, THEMES, MUSIC_STYLES, FORMATS, resolveSize, normalizeConfig } from './project.js';
|
|
5
|
+
import { layoutAreas } from '../engine/layout.js';
|
|
6
|
+
import { ScriptError } from './script.js';
|
|
7
|
+
import { prepare, makeState } from './pipeline.js';
|
|
8
|
+
import { render } from './render.js';
|
|
9
|
+
import { exportPlayer } from './export.js';
|
|
10
|
+
import { check, stills, sheet, verify } from './qa.js';
|
|
11
|
+
import { startServer, ROOT } from './server.js';
|
|
12
|
+
import { VOICES, LANGUAGES, voiceLanguage, loadTTS, loadASR, cacheRoot, ttsDtype, TTS_SAMPLE_RATE, MULTILINGUAL_ASR_MODEL } from './models.js';
|
|
13
|
+
import { espeakVersion, misakiAvailable, phonemize, generateSpeech } from './phonemes.js';
|
|
14
|
+
import { writeWav } from './wav.js';
|
|
15
|
+
import { ffmpegVersion } from './ffmpeg.js';
|
|
16
|
+
import { findChrome } from './browser.js';
|
|
17
|
+
import { generateImage, imageLog, imageSpend, IMAGE_MODELS } from './images.js';
|
|
18
|
+
import { elevenVoices, elevenUsage, elevenSpeed } from './elevenlabs.js';
|
|
19
|
+
import { capture } from './capture.js';
|
|
20
|
+
|
|
21
|
+
const VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version;
|
|
22
|
+
|
|
23
|
+
const HELP = `explainroo ${VERSION}: narrated explainer videos from code
|
|
24
|
+
|
|
25
|
+
Usage: explainroo <command> [project] [options]
|
|
26
|
+
|
|
27
|
+
Make a video
|
|
28
|
+
init <dir> create a project (--theme, --size, --pace, --language en|es|fr|it|pt-br|hi|ja|zh, --voice, --title)
|
|
29
|
+
voice [project] make the narration (Kokoro, ElevenLabs or a recording) and word timings
|
|
30
|
+
preview [project] live preview in your browser, reloads on save (--port, --size)
|
|
31
|
+
still [project] [t…] PNG stills: "12.5", "scene", "scene@2.4" (default: end of every scene; --size, --transparent)
|
|
32
|
+
sheet [project] contact sheet of the whole video (--scene id, --every s, --size)
|
|
33
|
+
check [project] find layout, timing and pronunciation problems (--view-width pixels, --size)
|
|
34
|
+
render [project] write the video with subtitles, chapters and a cover (--format mp4|gif|webm|mov,
|
|
35
|
+
--transparent, --size, --draft, --from s, --to s, --workers n, --out file)
|
|
36
|
+
verify [project] check the video: loudness, black frames, narration (--file)
|
|
37
|
+
export [project] write a web player folder (--out dir, default: out/player/)
|
|
38
|
+
|
|
39
|
+
Product demos
|
|
40
|
+
capture [project] <url> save screenshots, wording, colors, fonts and logo of a live site (--mobile)
|
|
41
|
+
|
|
42
|
+
Images (optional, needs an OpenRouter API key)
|
|
43
|
+
image [project] <name> "<what to draw>" save an illustration as assets/<name>.png
|
|
44
|
+
(--model best|cheap, --aspect 16:9, --ref assets/a.png,assets/b.png, --no-style)
|
|
45
|
+
images [project] list generated images and what they cost
|
|
46
|
+
|
|
47
|
+
Reference
|
|
48
|
+
voices [project] list Kokoro voices (--language es for one language, --elevenlabs for your ElevenLabs key)
|
|
49
|
+
say "text" hear a Kokoro voice (--voice am_michael, --speed 1, --out sample.wav)
|
|
50
|
+
themes list looks
|
|
51
|
+
formats list sizes for YouTube, Shorts, TikTok, Reels, Instagram, LinkedIn
|
|
52
|
+
icons <word…> search the 1,800+ built-in icons
|
|
53
|
+
doctor check ffmpeg, Chrome, espeak-ng, misaki and models (--fetch downloads English models)
|
|
54
|
+
|
|
55
|
+
Options: --size <size> overrides video.json for preview, still, sheet, check and render.
|
|
56
|
+
Size outputs get a suffix, like video-tiktok.mp4. --out still wins.
|
|
57
|
+
--json for machine-readable output. The project defaults to the current folder.
|
|
58
|
+
Docs: AGENTS.md (for coding agents) and https://www.explainroo.com/docs/`;
|
|
59
|
+
|
|
60
|
+
function parseArgs(argv) {
|
|
61
|
+
const pos = [];
|
|
62
|
+
const flags = {};
|
|
63
|
+
for (let i = 0; i < argv.length; i++) {
|
|
64
|
+
const a = argv[i];
|
|
65
|
+
if (a.startsWith('--')) {
|
|
66
|
+
const eq = a.indexOf('=');
|
|
67
|
+
if (eq !== -1) flags[a.slice(2, eq)] = a.slice(eq + 1);
|
|
68
|
+
else if (i + 1 < argv.length && !argv[i + 1].startsWith('--') && !BOOL.has(a.slice(2))) flags[a.slice(2)] = argv[++i];
|
|
69
|
+
else flags[a.slice(2)] = true;
|
|
70
|
+
} else if (a === '-h') flags.help = true;
|
|
71
|
+
else pos.push(a);
|
|
72
|
+
}
|
|
73
|
+
return { pos, flags };
|
|
74
|
+
}
|
|
75
|
+
const BOOL = new Set(['json', 'draft', 'transparent', 'force', 'fetch', 'help', 'version', 'quiet', 'open', 'no-style', 'elevenlabs', 'mobile']);
|
|
76
|
+
|
|
77
|
+
function num(v, name) {
|
|
78
|
+
if (v === undefined) return undefined;
|
|
79
|
+
if (v === true) throw new ProjectError(`--${name} needs a value`);
|
|
80
|
+
const n = Number(v);
|
|
81
|
+
if (!Number.isFinite(n)) throw new ProjectError(`--${name} must be a number`);
|
|
82
|
+
return n;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function main(argv) {
|
|
86
|
+
const { pos, flags } = parseArgs(argv);
|
|
87
|
+
const cmd = pos.shift();
|
|
88
|
+
const json = !!flags.json;
|
|
89
|
+
const log = json || flags.quiet ? () => {} : (m) => process.stderr.write(`${m}\n`);
|
|
90
|
+
const print = (human, data) => {
|
|
91
|
+
if (json) process.stdout.write(JSON.stringify(data, null, 2) + '\n');
|
|
92
|
+
else if (human) process.stdout.write(human + '\n');
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
if (!cmd || cmd === 'help' || flags.help) {
|
|
96
|
+
process.stdout.write(HELP + '\n');
|
|
97
|
+
return 0;
|
|
98
|
+
}
|
|
99
|
+
if (cmd === 'version' || flags.version) {
|
|
100
|
+
print(VERSION, { version: VERSION });
|
|
101
|
+
return 0;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
try {
|
|
105
|
+
switch (cmd) {
|
|
106
|
+
case 'init': return init(pos[0], flags, print);
|
|
107
|
+
case 'capture': {
|
|
108
|
+
if (pos.length < 1 || pos.length > 2) throw new ProjectError('usage: explainroo capture [project] <url> [--mobile] [--json]');
|
|
109
|
+
const r = await capture(pos.length === 2 ? pos[0] : undefined, pos.at(-1), { mobile: !!flags.mobile });
|
|
110
|
+
const families = r.fonts.families.map((f) => f.family).join(', ') || 'none found';
|
|
111
|
+
print(`saved:\n${r.files.map((f) => ' ' + f).join('\n')}\naccent: ${r.colors.accent || 'none found'}\nfonts: ${families}\nlogo: ${r.logo.picked || 'none found'}\n${r.notes.join('\n')}\nPaste into video.json:\n${JSON.stringify(r.suggestion, null, 2)}\nOpen the screenshots and check them before you use them.`, r);
|
|
112
|
+
return 0;
|
|
113
|
+
}
|
|
114
|
+
case 'voice': {
|
|
115
|
+
const project = loadProject(pos[0]);
|
|
116
|
+
const before = elevenUsage(project).length;
|
|
117
|
+
const { voices, timeline } = await prepare(project, { log, force: !!flags.force });
|
|
118
|
+
const characters = elevenUsage(project).slice(before).reduce((n, e) => n + e.characters, 0);
|
|
119
|
+
const rows = project.script.scenes.map((s) => {
|
|
120
|
+
const v = voices[s.id];
|
|
121
|
+
return { scene: s.id, voice: v.duration, confirmed: v.matchRate, unconfirmed: v.unmatched, marks: v.marks,
|
|
122
|
+
...(project.config.voice.provider === 'recording' && v.matchRate < 0.85 ? { message: 'The recording does not match script.md here. Make script.md say what was actually said.' } : {}) };
|
|
123
|
+
});
|
|
124
|
+
const mismatch = project.config.voice.provider === 'recording' && rows.some((r) => r.confirmed < 0.85)
|
|
125
|
+
? '\nThe recording does not match script.md in those scenes. Make script.md say what was actually said.' : '';
|
|
126
|
+
const isEleven = project.config.voice.provider === 'elevenlabs';
|
|
127
|
+
const wanted = project.config.speed * project.config.pace;
|
|
128
|
+
const speed = elevenSpeed(wanted);
|
|
129
|
+
const speedNote = isEleven && speed !== wanted ? `\nElevenLabs speed ${wanted.toFixed(2)} is outside 0.7 to 1.2; using ${speed}.` : '';
|
|
130
|
+
const usage = isEleven ? `\nElevenLabs: ${characters} characters used` : '';
|
|
131
|
+
print(rows.map((r) => `${r.scene.padEnd(18)} ${r.voice.toFixed(1).padStart(5)}s ${Math.round(r.confirmed * 100)}% confirmed${r.unconfirmed.length ? ' unconfirmed: ' + r.unconfirmed.slice(0, 6).join(', ') : ''}`).join('\n') + `\ntotal ${timeline.duration.toFixed(1)}s` + mismatch + usage + speedNote, { scenes: rows, duration: timeline.duration, ...(isEleven ? { characters, speed, ...(speed !== wanted ? { requested_speed: wanted } : {}) } : {}) });
|
|
132
|
+
return 0;
|
|
133
|
+
}
|
|
134
|
+
case 'preview': return await preview(pos[0], flags, log);
|
|
135
|
+
case 'still': {
|
|
136
|
+
const isProject = pos[0] && fs.existsSync(path.join(pos[0], 'video.json'));
|
|
137
|
+
const project = loadProject(isProject ? pos.shift() : undefined, { size: textFlag(flags, 'size') });
|
|
138
|
+
const list = await stills(project, pos, { log, scale: num(flags.scale, 'scale') ?? 1, transparent: !!flags.transparent });
|
|
139
|
+
print(list.map((s) => `${s.label.padEnd(24)} ${s.file}`).join('\n'), { stills: list });
|
|
140
|
+
return 0;
|
|
141
|
+
}
|
|
142
|
+
case 'sheet': {
|
|
143
|
+
const project = loadProject(pos[0], { size: textFlag(flags, 'size') });
|
|
144
|
+
const r = await sheet(project, { scene: flags.scene, every: num(flags.every, 'every'), cols: num(flags.cols, 'cols'), log });
|
|
145
|
+
print(`${r.file} (${r.frames} frames)`, r);
|
|
146
|
+
return 0;
|
|
147
|
+
}
|
|
148
|
+
case 'check': {
|
|
149
|
+
const project = loadProject(pos[0], { size: textFlag(flags, 'size') });
|
|
150
|
+
const r = await check(project, { log, step: num(flags.step, 'step') ?? 0.25, viewWidth: num(flags['view-width'], 'view-width') ?? null });
|
|
151
|
+
const errors = r.issues.filter((i) => i.level === 'error').length;
|
|
152
|
+
const human = r.issues.length
|
|
153
|
+
? r.issues.map((i) => `${i.level.toUpperCase().padEnd(5)} ${i.scene ?? ''}${i.t !== null && i.t !== undefined ? ' @' + i.t + 's' : ''}: ${i.message}`).join('\n') + `\n${errors} error(s), ${r.issues.length - errors} other finding(s) in ${r.scenes} scenes (${r.duration.toFixed(1)}s)`
|
|
154
|
+
: `no problems found in ${r.scenes} scenes (${r.duration.toFixed(1)}s)`;
|
|
155
|
+
print(human, r);
|
|
156
|
+
return errors ? 1 : 0;
|
|
157
|
+
}
|
|
158
|
+
case 'render': {
|
|
159
|
+
const project = loadProject(pos[0], { size: textFlag(flags, 'size') });
|
|
160
|
+
const r = await render(project, { log, draft: !!flags.draft, transparent: !!flags.transparent, from: num(flags.from, 'from'), to: num(flags.to, 'to'), workers: num(flags.workers, 'workers'), scale: num(flags.scale, 'scale'), out: textFlag(flags, 'out'), format: textFlag(flags, 'format') });
|
|
161
|
+
print([r.out, r.subtitles?.srt, r.subtitles?.vtt, r.chapters, r.cover].filter(Boolean).map((f) => path.relative(process.cwd(), f) || f).join('\n'), r);
|
|
162
|
+
return 0;
|
|
163
|
+
}
|
|
164
|
+
case 'export': {
|
|
165
|
+
const project = loadProject(pos[0]);
|
|
166
|
+
const r = await exportPlayer(project, { log, out: textFlag(flags, 'out') });
|
|
167
|
+
print(`${r.out} (${r.duration.toFixed(1)}s)`, r);
|
|
168
|
+
return 0;
|
|
169
|
+
}
|
|
170
|
+
case 'verify': {
|
|
171
|
+
const project = loadProject(pos[0]);
|
|
172
|
+
const r = await verify(project, { file: flags.file, log });
|
|
173
|
+
const lines = [
|
|
174
|
+
`${r.file}: ${r.duration}s, ${r.video ? `${r.video.width}x${r.video.height}` : 'no video'}, loudness ${r.loudness?.integrated ?? '?'} LUFS, true peak ${r.loudness?.truePeak ?? '?'} dBFS`,
|
|
175
|
+
r.speech ? `narration understood: ${Math.round(r.speech.matchRate * 100)}%` : '',
|
|
176
|
+
...r.issues.map((i) => `${i.level.toUpperCase().padEnd(5)} ${i.message}`),
|
|
177
|
+
].filter(Boolean);
|
|
178
|
+
print(lines.join('\n'), r);
|
|
179
|
+
return r.issues.some((i) => i.level === 'error') ? 1 : 0;
|
|
180
|
+
}
|
|
181
|
+
case 'image': {
|
|
182
|
+
const isProject = pos[0] && fs.existsSync(path.join(pos[0], 'video.json'));
|
|
183
|
+
const project = loadProject(isProject ? pos.shift() : undefined);
|
|
184
|
+
const [name, ...rest] = pos;
|
|
185
|
+
const r = await generateImage(project, {
|
|
186
|
+
name,
|
|
187
|
+
prompt: rest.join(' '),
|
|
188
|
+
model: flags.model,
|
|
189
|
+
aspect: flags.aspect,
|
|
190
|
+
refs: flags.ref ? String(flags.ref).split(',').map((x) => x.trim()).filter(Boolean) : [],
|
|
191
|
+
style: flags['no-style'] ? false : flags.style,
|
|
192
|
+
log,
|
|
193
|
+
});
|
|
194
|
+
print(`${r.file} ${r.model} ${r.cost_usd !== null ? '$' + r.cost_usd.toFixed(4) : 'cost unknown'} (images so far: $${r.total_usd.toFixed(4)})\nOpen the image and check it before you use it.`, r);
|
|
195
|
+
return 0;
|
|
196
|
+
}
|
|
197
|
+
case 'images': {
|
|
198
|
+
const project = loadProject(pos[0]);
|
|
199
|
+
const list = imageLog(project);
|
|
200
|
+
const total = imageSpend(project);
|
|
201
|
+
print(list.length ? list.map((e) => `${e.time.slice(0, 16)} ${e.file.padEnd(28)} ${e.model.padEnd(32)} ${e.cost_usd !== null ? '$' + e.cost_usd.toFixed(4) : '?'}`).join('\n') + `\n${list.length} image request(s), $${total.toFixed(4)}` : 'no images generated yet', { images: list, total_usd: total, models: IMAGE_MODELS });
|
|
202
|
+
return 0;
|
|
203
|
+
}
|
|
204
|
+
case 'voices': {
|
|
205
|
+
const language = textFlag(flags, 'language');
|
|
206
|
+
if (language !== undefined) normalizeConfig({ language });
|
|
207
|
+
if (flags.elevenlabs) {
|
|
208
|
+
const voices = await elevenVoices(path.resolve(pos[0] || '.'));
|
|
209
|
+
print(voices.map((v) => `${v.name} ${v.id} ${Object.entries(v.labels).map(([k, x]) => `${k}: ${x}`).join(', ')}`).join('\n'), { voices });
|
|
210
|
+
} else {
|
|
211
|
+
const voices = Object.fromEntries(Object.entries(VOICES).filter(([id]) => language === undefined || voiceLanguage(id) === language));
|
|
212
|
+
print(Object.entries(voices).map(([k, v]) => `${k.padEnd(12)} ${voiceLanguage(k).padEnd(6)} ${v}`).join('\n') + '\nUse voices --elevenlabs for ElevenLabs, or set voice to { "provider": "recording", "src": "assets/narration.wav" } in video.json.', { voices, languages: Object.fromEntries(Object.keys(voices).map(id => [id, voiceLanguage(id)])) });
|
|
213
|
+
}
|
|
214
|
+
return 0;
|
|
215
|
+
}
|
|
216
|
+
case 'say': return await say(pos.join(' '), flags, log, print);
|
|
217
|
+
case 'themes': {
|
|
218
|
+
const desc = {
|
|
219
|
+
paper: 'hand-drawn marker on warm paper; brush transitions; warm music',
|
|
220
|
+
clean: 'crisp flat product style, cards and soft shadows; slide transitions; upbeat music',
|
|
221
|
+
chalk: 'chalk on a green board with hatched fills; brush transitions; calm music',
|
|
222
|
+
blueprint: 'white technical drafting on blueprint blue with a grid; wipe transitions; tech music',
|
|
223
|
+
midnight: 'dark developer look with glowing accents; zoom transitions; tech music',
|
|
224
|
+
editorial: 'serif headlines and fine lines on warm paper, like a magazine; fade transitions; calm music',
|
|
225
|
+
};
|
|
226
|
+
print(THEMES.map((t) => `${t.padEnd(10)} ${desc[t]}`).join('\n') + `\n\nCustom looks: set theme in video.json to a relative .json file that extends a built-in look.\nmusic styles: ${MUSIC_STYLES.join(', ')}`, { themes: desc, music: MUSIC_STYLES });
|
|
227
|
+
return 0;
|
|
228
|
+
}
|
|
229
|
+
case 'formats': {
|
|
230
|
+
// The free area for content with the defaults (watermark on, captions
|
|
231
|
+
// as "auto" decides), the same box scenes get as s.safe.
|
|
232
|
+
const info = Object.entries(FORMATS).map(([name, f]) => {
|
|
233
|
+
const cfg = normalizeConfig({ size: name });
|
|
234
|
+
const { safe } = layoutAreas(cfg, cfg.width, cfg.height);
|
|
235
|
+
return { name, width: f.size[0], height: f.size[1], use: f.use, captions: cfg.captions, content: { x: safe.x, y: safe.y, w: safe.w, h: safe.h } };
|
|
236
|
+
});
|
|
237
|
+
const rows = info.map((r) => `${r.name.padEnd(10)} ${`${r.width}x${r.height}`.padEnd(10)} ${r.use}\n${''.padEnd(22)}content area ${r.content.w}x${r.content.h} at ${r.content.x},${r.content.y}${r.captions ? ', captions below it' : ''}`);
|
|
238
|
+
print(rows.join('\n') + '\n\nAlso: 16:9, 9:16, 1:1, 4:5 or WIDTHxHEIGHT. Set it with "size" in video.json or --size on init, preview, still, sheet, check or render.', { formats: info });
|
|
239
|
+
return 0;
|
|
240
|
+
}
|
|
241
|
+
case 'icons': return icons(pos, print);
|
|
242
|
+
case 'doctor': return await doctor(flags, log, print);
|
|
243
|
+
default:
|
|
244
|
+
process.stderr.write(`unknown command "${cmd}"\n\n${HELP}\n`);
|
|
245
|
+
return 2;
|
|
246
|
+
}
|
|
247
|
+
} catch (e) {
|
|
248
|
+
if (e instanceof ProjectError || e instanceof ScriptError) {
|
|
249
|
+
if (json) print(null, { error: e.message });
|
|
250
|
+
else process.stderr.write(`error: ${e.message}\n`);
|
|
251
|
+
return 1;
|
|
252
|
+
}
|
|
253
|
+
if (json) print(null, { error: e.message, stack: e.stack });
|
|
254
|
+
else process.stderr.write(`error: ${e.message}\n`);
|
|
255
|
+
if (process.env.EXPLAINROO_DEBUG) process.stderr.write(`${e.stack}\n`);
|
|
256
|
+
return 1;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// A text flag given without a value (for example "--title" at the end of the
|
|
261
|
+
// line) parses as true. Name the flag instead of failing deep in string code.
|
|
262
|
+
function textFlag(flags, name) {
|
|
263
|
+
if (flags[name] === true) throw new ProjectError(`--${name} needs a value`);
|
|
264
|
+
return flags[name];
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function init(dir, flags, print) {
|
|
268
|
+
if (!dir) throw new ProjectError('usage: explainroo init <dir> [--theme paper] [--size youtube|tiktok|linkedin|...] [--pace 1.2] [--language es] [--voice af_heart] [--title "..."]');
|
|
269
|
+
const target = path.resolve(dir);
|
|
270
|
+
if (fs.existsSync(path.join(target, 'video.json'))) throw new ProjectError(`${target} already has a video.json`);
|
|
271
|
+
const theme = textFlag(flags, 'theme') || 'paper';
|
|
272
|
+
if (!THEMES.includes(theme)) throw new ProjectError(`theme must be one of ${THEMES.join(', ')}`);
|
|
273
|
+
const language = textFlag(flags, 'language') ?? 'en';
|
|
274
|
+
normalizeConfig({ language });
|
|
275
|
+
const voice = textFlag(flags, 'voice') || LANGUAGES[language];
|
|
276
|
+
if (!VOICES[voice]) throw new ProjectError(`voice "${voice}" does not exist. Run "explainroo voices".`);
|
|
277
|
+
const title = textFlag(flags, 'title') || path.basename(target).replace(/[-_]+/g, ' ').replace(/^\w/, (c) => c.toUpperCase());
|
|
278
|
+
const tpl = path.join(ROOT, 'templates', 'starter');
|
|
279
|
+
const size = textFlag(flags, 'size') || '16:9';
|
|
280
|
+
resolveSize(size);
|
|
281
|
+
const config = { title, theme, size, voice, music: true, captions: 'auto' };
|
|
282
|
+
if (flags.language !== undefined) config.language = language;
|
|
283
|
+
if (flags.pace !== undefined) config.pace = num(flags.pace, 'pace');
|
|
284
|
+
normalizeConfig(config);
|
|
285
|
+
// Create the folder only after every setting checks out, so a bad flag
|
|
286
|
+
// leaves nothing behind.
|
|
287
|
+
fs.mkdirSync(path.join(target, 'assets'), { recursive: true });
|
|
288
|
+
fs.writeFileSync(path.join(target, 'video.json'), JSON.stringify(config, null, 2) + '\n');
|
|
289
|
+
fs.writeFileSync(path.join(target, 'script.md'), fs.readFileSync(path.join(tpl, 'script.md'), 'utf8').replace('{{title}}', title));
|
|
290
|
+
fs.writeFileSync(path.join(target, 'scenes.js'), fs.readFileSync(path.join(tpl, 'scenes.js'), 'utf8').replace(/\{\{title\}\}/g, title.replace(/'/g, "\\'")));
|
|
291
|
+
fs.writeFileSync(path.join(target, '.gitignore'), 'build/\nout/\n');
|
|
292
|
+
print(`created ${target}\nnext: edit script.md and scenes.js, then run "explainroo preview ${dir}" or "explainroo render ${dir} --draft"`, { dir: target });
|
|
293
|
+
return 0;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
async function preview(dir, flags, log) {
|
|
297
|
+
const size = textFlag(flags, 'size');
|
|
298
|
+
let project = loadProject(dir, { size });
|
|
299
|
+
let { timeline } = await prepare(project, { log });
|
|
300
|
+
let state = makeState(project, timeline);
|
|
301
|
+
let lastError = null;
|
|
302
|
+
const server = await startServer({ projectDir: project.dir, getState: () => (lastError ? { ...state, error: lastError } : state), port: num(flags.port, 'port') ?? 4400 });
|
|
303
|
+
log(`preview: ${server.url} (Ctrl+C to stop)`);
|
|
304
|
+
const watched = ['video.json', 'script.md'];
|
|
305
|
+
const stamp = () => {
|
|
306
|
+
const files = watched.map((f) => path.join(project.dir, f));
|
|
307
|
+
// Read the current path too, so creating a missing look file clears its error.
|
|
308
|
+
try {
|
|
309
|
+
const { theme } = JSON.parse(fs.readFileSync(files[0], 'utf8'));
|
|
310
|
+
if (typeof theme === 'string' && theme.endsWith('.json')) files.push(path.resolve(project.dir, theme));
|
|
311
|
+
} catch {}
|
|
312
|
+
return files.map((f) => { try { const st = fs.statSync(f); return `${f}:${st.mtimeMs}:${st.size}`; } catch { return `${f}:missing`; } }).join('|');
|
|
313
|
+
};
|
|
314
|
+
let last = stamp();
|
|
315
|
+
let busy = false;
|
|
316
|
+
const timer = setInterval(async () => {
|
|
317
|
+
if (busy) return;
|
|
318
|
+
const now = stamp();
|
|
319
|
+
busy = true;
|
|
320
|
+
try {
|
|
321
|
+
if (now !== last) {
|
|
322
|
+
last = now;
|
|
323
|
+
log('script, settings or look changed, updating project');
|
|
324
|
+
project = loadProject(project.dir, { size });
|
|
325
|
+
({ timeline } = await prepare(project, { log }));
|
|
326
|
+
lastError = null;
|
|
327
|
+
}
|
|
328
|
+
state = makeState(project, timeline);
|
|
329
|
+
} catch (e) {
|
|
330
|
+
lastError = e.message;
|
|
331
|
+
log(`error: ${e.message}`);
|
|
332
|
+
} finally {
|
|
333
|
+
busy = false;
|
|
334
|
+
}
|
|
335
|
+
}, 700);
|
|
336
|
+
await new Promise((resolve) => {
|
|
337
|
+
const stop = () => resolve();
|
|
338
|
+
process.once('SIGINT', stop);
|
|
339
|
+
process.once('SIGTERM', stop);
|
|
340
|
+
});
|
|
341
|
+
clearInterval(timer);
|
|
342
|
+
await server.close();
|
|
343
|
+
return 0;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async function say(text, flags, log, print) {
|
|
347
|
+
if (!text) throw new ProjectError('usage: explainroo say "text to speak" [--voice af_heart] [--speed 1] [--out sample.wav]');
|
|
348
|
+
const voice = textFlag(flags, 'voice') || 'af_heart';
|
|
349
|
+
if (!VOICES[voice]) throw new ProjectError(`voice "${voice}" does not exist. Run "explainroo voices".`);
|
|
350
|
+
const tts = await loadTTS({ log });
|
|
351
|
+
const language = voiceLanguage(voice);
|
|
352
|
+
const phonemes = language === 'en' ? undefined : (await phonemize([text], language))[0];
|
|
353
|
+
const audio = await generateSpeech(tts, text, { language, voice, speed: num(flags.speed, 'speed') ?? 1, phonemes });
|
|
354
|
+
const out = path.resolve(textFlag(flags, 'out') || `${voice}.wav`);
|
|
355
|
+
writeWav(out, audio.audio, audio.sampling_rate || TTS_SAMPLE_RATE);
|
|
356
|
+
print(out, { file: out, voice });
|
|
357
|
+
return 0;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function icons(words, print) {
|
|
361
|
+
const all = JSON.parse(fs.readFileSync(path.join(ROOT, 'engine', 'icons', 'lucide-tags.json'), 'utf8'));
|
|
362
|
+
const { aliases = {} } = JSON.parse(fs.readFileSync(path.join(ROOT, 'engine', 'icons', 'lucide.json'), 'utf8'));
|
|
363
|
+
for (const [alias, target] of Object.entries(aliases)) all[target] = [...(all[target] || []), alias.replace(/-/g, ' ')];
|
|
364
|
+
const q = words.map((w) => w.toLowerCase());
|
|
365
|
+
if (!q.length) {
|
|
366
|
+
print(`${Object.keys(all).length} icons. Search with: explainroo icons <word…>`, { count: Object.keys(all).length });
|
|
367
|
+
return 0;
|
|
368
|
+
}
|
|
369
|
+
const scored = Object.entries(all)
|
|
370
|
+
.map(([name, tags]) => {
|
|
371
|
+
let score = 0;
|
|
372
|
+
for (const w of q) {
|
|
373
|
+
if (name === w) score += 10;
|
|
374
|
+
else if (name.split('-').includes(w)) score += 6;
|
|
375
|
+
else if (name.includes(w)) score += 3;
|
|
376
|
+
if (tags.some((t) => t === w)) score += 4;
|
|
377
|
+
else if (tags.some((t) => t.includes(w))) score += 1;
|
|
378
|
+
}
|
|
379
|
+
return { name, score, tags };
|
|
380
|
+
})
|
|
381
|
+
.filter((x) => x.score > 0)
|
|
382
|
+
.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name))
|
|
383
|
+
.slice(0, 40);
|
|
384
|
+
print(scored.map((x) => `${x.name.padEnd(28)} ${x.tags.slice(0, 6).join(', ')}`).join('\n') || `no icons match "${words.join(' ')}"`, { icons: scored.map((x) => x.name) });
|
|
385
|
+
return 0;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
async function doctor(flags, log, print) {
|
|
389
|
+
const rows = [];
|
|
390
|
+
const add = (name, ok, detail) => rows.push({ name, ok, detail });
|
|
391
|
+
// The voice library (kokoro-js) needs import.meta.dirname, added in Node 20.11.
|
|
392
|
+
const [maj, min] = process.versions.node.split('.').map(Number);
|
|
393
|
+
const nodeOk = maj > 20 || (maj === 20 && min >= 11);
|
|
394
|
+
add('node', nodeOk, `v${process.versions.node}${nodeOk ? '' : ' (need 20.11 or newer)'}`);
|
|
395
|
+
const ff = ffmpegVersion();
|
|
396
|
+
add('ffmpeg', !!ff, ff || 'not found; install ffmpeg or set EXPLAINROO_FFMPEG');
|
|
397
|
+
const espeak = espeakVersion();
|
|
398
|
+
add('espeak-ng', true, espeak || 'not found; only needed for Spanish, French, Italian, Portuguese and Hindi');
|
|
399
|
+
for (const [language, name] of [['ja', 'Japanese'], ['zh', 'Chinese']]) {
|
|
400
|
+
add(`misaki ${language}`, true, misakiAvailable(language) ? `Python with misaki for ${name}` : `not found; only needed for ${name}`);
|
|
401
|
+
}
|
|
402
|
+
try {
|
|
403
|
+
add('chrome', true, findChrome());
|
|
404
|
+
} catch (e) {
|
|
405
|
+
add('chrome', false, e.message);
|
|
406
|
+
}
|
|
407
|
+
const models = path.join(cacheRoot(), 'models', 'onnx-community');
|
|
408
|
+
const has = (n) => fs.existsSync(path.join(models, n));
|
|
409
|
+
if (flags.fetch) {
|
|
410
|
+
log('downloading English speech models (about 400 MB the first time)');
|
|
411
|
+
log('other languages fetch their speech check model on first use, and Japanese and Chinese their fonts');
|
|
412
|
+
await loadTTS({ log });
|
|
413
|
+
await loadASR({ log });
|
|
414
|
+
}
|
|
415
|
+
add('voice model', has('Kokoro-82M-v1.0-ONNX'), has('Kokoro-82M-v1.0-ONNX') ? `Kokoro 82M (${ttsDtype()}) in ${models}` : 'not downloaded yet; "explainroo doctor --fetch" or the first voice run fetches it');
|
|
416
|
+
add('speech check model', has('whisper-base.en_timestamped'), has('whisper-base.en_timestamped') ? 'Whisper base.en' : 'not downloaded yet; fetched on first use');
|
|
417
|
+
add('language model', has(MULTILINGUAL_ASR_MODEL.split('/')[1]), 'Whisper small for languages other than English; downloaded on first use, not by --fetch');
|
|
418
|
+
const ok = rows.every((r) => r.ok || r.name.includes('model'));
|
|
419
|
+
print(rows.map((r) => `${r.ok ? 'ok ' : 'FAIL'} ${r.name.padEnd(20)} ${r.detail}`).join('\n'), { ok, checks: rows });
|
|
420
|
+
return ok ? 0 : 1;
|
|
421
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { ffmpeg, probe } from './ffmpeg.js';
|
|
4
|
+
|
|
5
|
+
export const VIDEO_FILE = /\.(mp4|mov|webm|m4v)$/i;
|
|
6
|
+
|
|
7
|
+
export async function extractClip(file, dir, fps) {
|
|
8
|
+
const input = await probe(file);
|
|
9
|
+
const video = input.streams.find((s) => s.codec_type === 'video');
|
|
10
|
+
if (!video) throw new Error('this clip has no video. Use an MP4, MOV, WebM or M4V with video.');
|
|
11
|
+
await ffmpeg(['-loglevel', 'error', '-i', file, '-map', '0:v:0', '-vf', `fps=${fps},scale=min(1920\\,iw):-1`, '-q:v', '2', '-threads', '1', '-start_number', '0', path.join(dir, '%08d.jpg')]);
|
|
12
|
+
const frames = fs.readdirSync(dir).filter((n) => n.endsWith('.jpg')).length;
|
|
13
|
+
if (!frames) throw new Error('this clip has no frames. Use a video with at least one frame.');
|
|
14
|
+
const frame = await probe(path.join(dir, '00000000.jpg'));
|
|
15
|
+
const { width, height } = frame.streams[0];
|
|
16
|
+
const hasAudio = input.streams.some((s) => s.codec_type === 'audio');
|
|
17
|
+
if (hasAudio) await ffmpeg(['-loglevel', 'error', '-i', file, '-map', '0:a:0', '-vn', '-ar', '48000', '-ac', '1', '-c:a', 'pcm_s16le', path.join(dir, 'audio.wav')]);
|
|
18
|
+
return { frames, fps, width, height, duration: frames / fps, hasAudio };
|
|
19
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
4
|
+
import { findEnv } from './env.js';
|
|
5
|
+
import { ProjectError } from './project.js';
|
|
6
|
+
|
|
7
|
+
export function elevenSpeed(speed) {
|
|
8
|
+
return Math.max(0.7, Math.min(1.2, speed));
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function apiKey(dir) {
|
|
12
|
+
const key = findEnv('ELEVENLABS_API_KEY', dir);
|
|
13
|
+
if (!key) throw new ProjectError('ElevenLabs needs an API key. Ask the user for one from elevenlabs.io, then set ELEVENLABS_API_KEY or put ELEVENLABS_API_KEY=... in a .env file in the project or explainroo folder.');
|
|
14
|
+
return key;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async function request(url, key, options = {}) {
|
|
18
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
19
|
+
let res;
|
|
20
|
+
try {
|
|
21
|
+
res = await fetch(url, { ...options, signal: AbortSignal.timeout(120000), headers: { 'xi-api-key': key, 'Content-Type': 'application/json' } });
|
|
22
|
+
} catch {
|
|
23
|
+
throw new ProjectError('ElevenLabs did not answer. Check your connection and try again.');
|
|
24
|
+
}
|
|
25
|
+
if (res.ok) return res;
|
|
26
|
+
const body = await res.json().catch(() => null);
|
|
27
|
+
const status = body?.detail?.status;
|
|
28
|
+
if (status === 'quota_exceeded' || res.status === 402) throw new ProjectError('the ElevenLabs account has no characters left. Ask the user to check their plan.');
|
|
29
|
+
if (status === 'voice_not_found' || res.status === 404) throw new ProjectError('ElevenLabs could not find that voice id. Run "explainroo voices --elevenlabs" and check voice.id.');
|
|
30
|
+
if (res.status === 401 || res.status === 403) throw new ProjectError('ElevenLabs rejected the API key. Ask the user to check the key and its permissions.');
|
|
31
|
+
if ((res.status === 429 || res.status >= 500) && attempt < 2) {
|
|
32
|
+
await sleep(250 * 2 ** attempt);
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
throw new ProjectError(res.status === 429 || res.status >= 500
|
|
36
|
+
? 'ElevenLabs is busy. Try again in a moment.'
|
|
37
|
+
: 'ElevenLabs could not make the voice. Check voice.id and voice.model in video.json.');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function decodePCM(buffer) {
|
|
42
|
+
const bytes = Buffer.from(buffer);
|
|
43
|
+
if (!bytes.length || bytes.length % 2) throw new ProjectError('ElevenLabs returned unreadable audio. Try the voice command again.');
|
|
44
|
+
const samples = new Float32Array(bytes.length / 2);
|
|
45
|
+
for (let i = 0; i < samples.length; i++) samples[i] = bytes.readInt16LE(i * 2) / 32768;
|
|
46
|
+
return samples;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function elevenUsage(project) {
|
|
50
|
+
const file = path.join(project.paths.voice, 'elevenlabs-usage.jsonl');
|
|
51
|
+
return fs.existsSync(file) ? fs.readFileSync(file, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)) : [];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function elevenSpeech(project, scene, text, { previous, next } = {}) {
|
|
55
|
+
const key = apiKey(project.dir);
|
|
56
|
+
const { voice, speed, pace } = project.config;
|
|
57
|
+
const res = await request(`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(voice.id)}?output_format=pcm_24000`, key, {
|
|
58
|
+
method: 'POST',
|
|
59
|
+
// Without voice_settings ElevenLabs uses the voice's own saved settings.
|
|
60
|
+
body: JSON.stringify({ text, model_id: voice.model, ...(elevenSpeed(speed * pace) !== 1 ? { voice_settings: { speed: elevenSpeed(speed * pace) } } : {}),
|
|
61
|
+
...(previous && voice.model !== 'eleven_v3' ? { previous_text: previous } : {}), ...(next && voice.model !== 'eleven_v3' ? { next_text: next } : {}) }),
|
|
62
|
+
});
|
|
63
|
+
const entry = { time: new Date().toISOString(), scene, characters: [...text].length, model: voice.model, voice_id: voice.id };
|
|
64
|
+
fs.mkdirSync(project.paths.voice, { recursive: true });
|
|
65
|
+
fs.appendFileSync(path.join(project.paths.voice, 'elevenlabs-usage.jsonl'), JSON.stringify(entry) + '\n');
|
|
66
|
+
let buffer;
|
|
67
|
+
try { buffer = await res.arrayBuffer(); }
|
|
68
|
+
catch { throw new ProjectError('ElevenLabs audio download failed. Check your connection and try again.'); }
|
|
69
|
+
return { audio: decodePCM(buffer), sampling_rate: 24000 };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function elevenVoices(dir) {
|
|
73
|
+
const key = apiKey(dir);
|
|
74
|
+
const voices = [];
|
|
75
|
+
let token;
|
|
76
|
+
do {
|
|
77
|
+
const url = new URL('https://api.elevenlabs.io/v2/voices');
|
|
78
|
+
url.searchParams.set('page_size', '100');
|
|
79
|
+
if (token) url.searchParams.set('next_page_token', token);
|
|
80
|
+
let data;
|
|
81
|
+
try { data = await (await request(url, key)).json(); }
|
|
82
|
+
catch (e) {
|
|
83
|
+
if (e instanceof ProjectError) throw e;
|
|
84
|
+
throw new ProjectError('ElevenLabs returned an unreadable voice list. Try again.');
|
|
85
|
+
}
|
|
86
|
+
voices.push(...data.voices.map((v) => ({ name: v.name, id: v.voice_id, labels: v.labels || {} })));
|
|
87
|
+
token = data.has_more ? data.next_page_token : null;
|
|
88
|
+
} while (token);
|
|
89
|
+
return voices;
|
|
90
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { ROOT } from './server.js';
|
|
4
|
+
|
|
5
|
+
export function readEnvFile(file, name) {
|
|
6
|
+
if (!fs.existsSync(file)) return null;
|
|
7
|
+
for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
|
|
8
|
+
const m = /^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=\s*(.*?)\s*$/.exec(line);
|
|
9
|
+
if (m && m[1] === name) return m[2].replace(/^["']|["']$/g, '').trim() || null;
|
|
10
|
+
}
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function findEnv(name, projectDir, root = ROOT) {
|
|
15
|
+
return process.env[name] || readEnvFile(path.join(projectDir, '.env'), name) || readEnvFile(path.join(root, '.env'), name);
|
|
16
|
+
}
|