@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,331 @@
|
|
|
1
|
+
// Loads and validates a video project folder:
|
|
2
|
+
// video.json settings
|
|
3
|
+
// script.md narration, one "## scene-id" per scene
|
|
4
|
+
// scenes.js one drawing function per scene id
|
|
5
|
+
// assets/ optional images (logos, screenshots)
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { parseScript } from './script.js';
|
|
9
|
+
import { VOICES, LANGUAGES, voiceLanguage } from './models.js';
|
|
10
|
+
import { THEMES as LOOKS } from '../engine/themes.js';
|
|
11
|
+
import { parseColor } from '../engine/util.js';
|
|
12
|
+
|
|
13
|
+
export const THEMES = Object.keys(LOOKS);
|
|
14
|
+
export const MUSIC_STYLES = ['warm', 'upbeat', 'calm', 'tech', 'playful'];
|
|
15
|
+
export const TRANSITIONS = ['auto', 'fade', 'slide', 'wipe', 'zoom', 'brush', 'cut'];
|
|
16
|
+
export const THEME_MUSIC = Object.fromEntries(THEMES.map((name) => [name, LOOKS[name].music]));
|
|
17
|
+
const ASPECTS = { '16:9': [1920, 1080], '9:16': [1080, 1920], '1:1': [1080, 1080], '4:5': [1080, 1350] };
|
|
18
|
+
|
|
19
|
+
// Named formats for the usual places a video goes. Vertical apps draw their
|
|
20
|
+
// own buttons, names and captions over the video; `safe` is the part of the
|
|
21
|
+
// frame they leave free, as fractions of the frame. The numbers follow the
|
|
22
|
+
// platforms' safe-zone templates as of 2026 and move a little with app updates.
|
|
23
|
+
export const FORMATS = {
|
|
24
|
+
youtube: { size: [1920, 1080], use: 'YouTube and other wide players' },
|
|
25
|
+
shorts: { size: [1080, 1920], use: 'YouTube Shorts', safe: { top: 0.15, right: 0.12, bottom: 0.35, left: 0.06 } },
|
|
26
|
+
tiktok: { size: [1080, 1920], use: 'TikTok', safe: { top: 0.125, right: 0.2, bottom: 0.34, left: 0.11 } },
|
|
27
|
+
reels: { size: [1080, 1920], use: 'Instagram and Facebook Reels', safe: { top: 0.14, right: 0.11, bottom: 0.35, left: 0.06 } },
|
|
28
|
+
vertical: { size: [1080, 1920], use: 'one file for Shorts, TikTok and Reels', safe: { top: 0.15, right: 0.2, bottom: 0.35, left: 0.11 } },
|
|
29
|
+
instagram: { size: [1080, 1350], use: 'Instagram and Facebook feed posts' },
|
|
30
|
+
linkedin: { size: [1080, 1350], use: 'the LinkedIn feed' },
|
|
31
|
+
square: { size: [1080, 1080], use: 'square posts on X, LinkedIn and Facebook' },
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export const DEFAULTS = {
|
|
35
|
+
title: null,
|
|
36
|
+
theme: 'paper',
|
|
37
|
+
size: '16:9',
|
|
38
|
+
fps: 30,
|
|
39
|
+
language: 'en',
|
|
40
|
+
voice: 'af_heart',
|
|
41
|
+
speed: 0.9,
|
|
42
|
+
pace: 1,
|
|
43
|
+
music: true,
|
|
44
|
+
sfx: true,
|
|
45
|
+
captions: 'auto',
|
|
46
|
+
cover: 'auto',
|
|
47
|
+
transition: 'auto',
|
|
48
|
+
camera: 'auto',
|
|
49
|
+
motionBlur: true,
|
|
50
|
+
lead: 0.35,
|
|
51
|
+
hold: 0.7,
|
|
52
|
+
end: 1.4,
|
|
53
|
+
sentenceGap: 0.3,
|
|
54
|
+
paragraphGap: 0.55,
|
|
55
|
+
loudness: -14,
|
|
56
|
+
seed: 1,
|
|
57
|
+
boil: 0,
|
|
58
|
+
watermark: 'explainroo.com',
|
|
59
|
+
images: null,
|
|
60
|
+
brand: null,
|
|
61
|
+
fonts: [],
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
// Settings for the UI kit (s.ui), for product demos in a brand's own look.
|
|
65
|
+
export const BRAND_KEYS = ['accent', 'background', 'ink', 'font', 'headline', 'logo', 'colors'];
|
|
66
|
+
// The UI kit's neutral colors that brand.colors can replace.
|
|
67
|
+
export const BRAND_COLORS = ['text', 'soft', 'muted', 'faint', 'line', 'field', 'surface', 'panel'];
|
|
68
|
+
const FONT_FILE = /\.(woff2?|ttf|otf)$/i;
|
|
69
|
+
const HEX = /^#[0-9a-f]{6}$/i;
|
|
70
|
+
|
|
71
|
+
export class ProjectError extends Error {}
|
|
72
|
+
|
|
73
|
+
function fail(msg) {
|
|
74
|
+
throw new ProjectError(msg);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const LOOK_KEYS = ['extends', 'name', 'dark', 'bg', 'ink', 'muted', 'surface', 'accent', 'colors', 'fonts', 'background', 'stroke', 'radius', 'transition', 'music', 'code', 'terminal', 'caption'];
|
|
78
|
+
const TEXTURES = ['paper', 'dots', 'chalk', 'grid', 'glow', 'plain'];
|
|
79
|
+
const BUILTIN_FONTS = [...new Set(JSON.parse(fs.readFileSync(new URL('../fonts/fonts.json', import.meta.url), 'utf8')).map((f) => f.family))];
|
|
80
|
+
|
|
81
|
+
function lookPath(theme) {
|
|
82
|
+
return typeof theme === 'string' && theme.endsWith('.json') && !path.isAbsolute(theme) && !path.win32.isAbsolute(theme);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function loadLook(dir, file, fonts = []) {
|
|
86
|
+
const bad = (key, message) => fail(`${file}: ${key} ${message}`);
|
|
87
|
+
let raw;
|
|
88
|
+
try {
|
|
89
|
+
raw = JSON.parse(fs.readFileSync(path.resolve(dir, file), 'utf8'));
|
|
90
|
+
} catch (e) {
|
|
91
|
+
if (e.code === 'ENOENT') bad('theme', 'file is missing. Check the path in video.json.');
|
|
92
|
+
bad('theme', `file could not be read as JSON: ${e.message}`);
|
|
93
|
+
}
|
|
94
|
+
const object = (value, key, keys) => {
|
|
95
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) bad(key, 'must be an object');
|
|
96
|
+
for (const k of Object.keys(value)) if (!keys.includes(k)) bad(`${key}.${k}`, `is unknown. Known: ${keys.join(', ')}`);
|
|
97
|
+
};
|
|
98
|
+
const oneOf = (value, key, values) => {
|
|
99
|
+
if (!values.includes(value)) bad(key, `must be one of ${values.join(', ')}`);
|
|
100
|
+
};
|
|
101
|
+
const number = (value, key, min, max) => {
|
|
102
|
+
if (!(typeof value === 'number' && Number.isFinite(value) && value >= min && value <= max)) bad(key, `must be a number between ${min} and ${max}`);
|
|
103
|
+
};
|
|
104
|
+
const color = (value, key, alpha = false) => {
|
|
105
|
+
const p = typeof value === 'string' && /^rgba\(\s*\d+(?:\.\d+)?\s*,\s*\d+(?:\.\d+)?\s*,\s*\d+(?:\.\d+)?\s*,\s*(?:\d+(?:\.\d+)?|\.\d+)\s*\)$/.test(value) ? parseColor(value) : null;
|
|
106
|
+
if (!(typeof value === 'string' && HEX.test(value)) && !(alpha && p && [p.r, p.g, p.b].every((v) => v <= 255) && p.a <= 1)) {
|
|
107
|
+
bad(key, `must be a color like "#2563eb"${alpha ? ' or "rgba(17,24,39,0.82)"' : ''}`);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
object(raw, 'look', LOOK_KEYS);
|
|
111
|
+
oneOf(raw.extends, 'extends', THEMES);
|
|
112
|
+
const name = raw.name === undefined ? path.basename(file, '.json') : raw.name;
|
|
113
|
+
if (!(typeof name === 'string' && name.trim()) || THEMES.includes(name)) bad('name', 'must be a non-empty name that is not a built-in look');
|
|
114
|
+
if (raw.dark !== undefined && typeof raw.dark !== 'boolean') bad('dark', 'must be true or false');
|
|
115
|
+
for (const k of ['bg', 'ink', 'muted', 'surface']) if (raw[k] !== undefined) color(raw[k], k);
|
|
116
|
+
if (raw.accent !== undefined) oneOf(raw.accent, 'accent', Object.keys(LOOKS.paper.colors));
|
|
117
|
+
if (raw.background !== undefined) oneOf(raw.background, 'background', TEXTURES);
|
|
118
|
+
if (raw.transition !== undefined) oneOf(raw.transition, 'transition', TRANSITIONS.filter((v) => v !== 'auto'));
|
|
119
|
+
if (raw.music !== undefined) oneOf(raw.music, 'music', MUSIC_STYLES);
|
|
120
|
+
if (raw.radius !== undefined) number(raw.radius, 'radius', 0, 200);
|
|
121
|
+
for (const group of ['colors', 'code', 'terminal', 'caption']) {
|
|
122
|
+
if (raw[group] === undefined) continue;
|
|
123
|
+
const base = LOOKS[raw.extends][group];
|
|
124
|
+
object(raw[group], group, Object.keys(base));
|
|
125
|
+
for (const [k, v] of Object.entries(raw[group])) color(v, `${group}.${k}`, String(base[k]).startsWith('rgba('));
|
|
126
|
+
}
|
|
127
|
+
if (raw.fonts !== undefined) {
|
|
128
|
+
object(raw.fonts, 'fonts', Object.keys(LOOKS.paper.fonts));
|
|
129
|
+
for (const [role, f] of Object.entries(raw.fonts)) {
|
|
130
|
+
const key = `fonts.${role}`;
|
|
131
|
+
object(f, key, ['family', 'weight']);
|
|
132
|
+
if (f.family !== undefined && ![...BUILTIN_FONTS, ...fonts.map((v) => v.family)].includes(f.family)) bad(`${key}.family`, `must be listed in video.json fonts or be built in. Built-in families: ${BUILTIN_FONTS.join(', ')}`);
|
|
133
|
+
if (f.weight !== undefined) {
|
|
134
|
+
number(f.weight, `${key}.weight`, 1, 1000);
|
|
135
|
+
if (!Number.isInteger(f.weight)) bad(`${key}.weight`, 'must be a whole number');
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (raw.stroke !== undefined) {
|
|
140
|
+
const ranges = { width: [0, 20], roughness: [0, 5], bowing: [0, 5], hachureGap: [1, 100], fillWeight: [0, 20], glow: [0, 100] };
|
|
141
|
+
object(raw.stroke, 'stroke', ['rough', ...Object.keys(ranges), 'fillStyle', 'texture']);
|
|
142
|
+
for (const [k, v] of Object.entries(raw.stroke)) {
|
|
143
|
+
if (ranges[k]) number(v, `stroke.${k}`, ...ranges[k]);
|
|
144
|
+
else if (k === 'rough' && typeof v !== 'boolean') bad('stroke.rough', 'must be true or false');
|
|
145
|
+
else if (k === 'fillStyle') oneOf(v, 'stroke.fillStyle', ['solid', 'hachure', 'cross-hatch', 'zigzag', 'dots']);
|
|
146
|
+
else if (k === 'texture') oneOf(v, 'stroke.texture', ['chalk']);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return { ...raw, name };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function resolveSize(size) {
|
|
153
|
+
if (FORMATS[size]) return { width: FORMATS[size].size[0], height: FORMATS[size].size[1], safe: FORMATS[size].safe || null };
|
|
154
|
+
if (ASPECTS[size]) return { width: ASPECTS[size][0], height: ASPECTS[size][1] };
|
|
155
|
+
const m = /^(\d{3,4})x(\d{3,4})$/.exec(String(size));
|
|
156
|
+
if (!m) fail(`size must be a format (${Object.keys(FORMATS).join(', ')}), a ratio (${Object.keys(ASPECTS).join(', ')}) or WIDTHxHEIGHT, not "${size}"`);
|
|
157
|
+
const width = Number(m[1]);
|
|
158
|
+
const height = Number(m[2]);
|
|
159
|
+
if (width % 2 || height % 2) fail('size width and height must be even numbers (H.264 needs that)');
|
|
160
|
+
return { width, height };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function normalizeConfig(raw, dir = '.') {
|
|
164
|
+
const cfg = { ...DEFAULTS, ...raw };
|
|
165
|
+
if (typeof cfg.language !== 'string' || !Object.hasOwn(LANGUAGES, cfg.language)) fail(`language must be one of ${Object.keys(LANGUAGES).join(', ')}`);
|
|
166
|
+
if (raw.voice === undefined) cfg.voice = LANGUAGES[cfg.language];
|
|
167
|
+
const unknown = Object.keys(raw).filter((k) => !(k in DEFAULTS) && !k.startsWith('_'));
|
|
168
|
+
if (unknown.length) fail(`video.json has unknown setting(s): ${unknown.join(', ')}. Known: ${Object.keys(DEFAULTS).join(', ')}`);
|
|
169
|
+
if (!THEMES.includes(cfg.theme) && !lookPath(cfg.theme)) fail(`theme must be one of ${THEMES.join(', ')} or a relative path to a .json look file, not "${cfg.theme}"`);
|
|
170
|
+
if (typeof cfg.voice === 'object') {
|
|
171
|
+
const v = cfg.voice;
|
|
172
|
+
if (!v || Array.isArray(v)) fail('voice must be a Kokoro id or an object with provider');
|
|
173
|
+
const keys = { kokoro: ['provider', 'id'], elevenlabs: ['provider', 'id', 'model'], recording: ['provider', 'src'] };
|
|
174
|
+
if (typeof v.provider !== 'string' || !Object.hasOwn(keys, v.provider)) fail('voice.provider must be kokoro, elevenlabs or recording');
|
|
175
|
+
const extra = Object.keys(v).filter((k) => !keys[v.provider].includes(k));
|
|
176
|
+
if (extra.length) fail(`voice has unknown setting(s): ${extra.join(', ')}. Known: ${keys[v.provider].join(', ')}`);
|
|
177
|
+
if (v.provider === 'recording') {
|
|
178
|
+
if (!(typeof v.src === 'string' && /^assets\/.+/.test(v.src) && !v.src.split('/').includes('..') && !v.src.includes('\\'))) {
|
|
179
|
+
fail('voice.src must be a file or folder inside assets/, with no ..');
|
|
180
|
+
}
|
|
181
|
+
} else if (!(typeof v.id === 'string' && v.id.trim())) fail('voice.id is required');
|
|
182
|
+
if (v.provider === 'kokoro') cfg.voice = v.id;
|
|
183
|
+
if (v.provider === 'elevenlabs') {
|
|
184
|
+
if (v.model !== undefined && !(typeof v.model === 'string' && v.model.trim())) fail('voice.model must be an ElevenLabs model id');
|
|
185
|
+
cfg.voice = { ...v, model: v.model ?? 'eleven_multilingual_v2' };
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (typeof cfg.voice === 'string') {
|
|
189
|
+
if (!Object.hasOwn(VOICES, cfg.voice)) fail(`voice "${cfg.voice}" does not exist. Run "explainroo voices" for the list.`);
|
|
190
|
+
if (voiceLanguage(cfg.voice) !== cfg.language) fail(`voice "${cfg.voice}" does not speak ${cfg.language}. Use ${Object.keys(VOICES).filter(id => voiceLanguage(id) === cfg.language).join(', ')}.`);
|
|
191
|
+
} else if (!cfg.voice || typeof cfg.voice !== 'object') fail('voice must be a Kokoro id or an object with provider');
|
|
192
|
+
if (typeof cfg.voice !== 'string' && raw.speed === undefined) cfg.speed = 1;
|
|
193
|
+
if (!(cfg.speed >= 0.6 && cfg.speed <= 1.6)) fail('speed must be between 0.6 and 1.6');
|
|
194
|
+
if (!(cfg.pace >= 0.7 && cfg.pace <= 1.6)) fail('pace must be between 0.7 and 1.6 (1 is normal, 1.3 is 30% faster)');
|
|
195
|
+
if (typeof cfg.voice === 'string' && cfg.speed * cfg.pace > 1.8) fail(`speed ${cfg.speed} times pace ${cfg.pace} makes the voice too fast; keep speed x pace at 1.8 or below`);
|
|
196
|
+
if (![24, 25, 30, 50, 60].includes(cfg.fps)) fail('fps must be 24, 25, 30, 50 or 60');
|
|
197
|
+
if (!TRANSITIONS.includes(cfg.transition)) fail(`transition must be one of ${TRANSITIONS.join(', ')}`);
|
|
198
|
+
if (!['auto', 'still'].includes(cfg.camera)) fail('camera must be "auto" (the camera follows the narration) or "still"');
|
|
199
|
+
if (typeof cfg.motionBlur !== 'boolean') fail('motionBlur must be true or false');
|
|
200
|
+
if (![true, false, 'minimal'].includes(cfg.sfx)) fail('sfx must be true, false or "minimal"');
|
|
201
|
+
if (![true, false, 'auto'].includes(cfg.captions)) fail('captions must be true, false or "auto"');
|
|
202
|
+
const cover = cfg.cover;
|
|
203
|
+
const [scene, at, extra] = typeof cover === 'string' ? cover.split('@') : [];
|
|
204
|
+
const coverTime = typeof cover === 'number' && Number.isFinite(cover) && cover >= 0;
|
|
205
|
+
const coverSpec = typeof cover === 'string' && (/^\d+(\.\d+)?$/.test(cover) || (
|
|
206
|
+
/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(scene) && extra === undefined &&
|
|
207
|
+
(at === undefined || at === '' || at === 'end' || at === 'start' || Number.isFinite(Number(at)))
|
|
208
|
+
));
|
|
209
|
+
if (!coverTime && !coverSpec) fail('cover must be "auto", seconds like 12.5, or a still spec like "intro@end"');
|
|
210
|
+
for (const k of ['lead', 'hold', 'end', 'sentenceGap', 'paragraphGap']) {
|
|
211
|
+
if (!(typeof cfg[k] === 'number' && cfg[k] >= 0 && cfg[k] <= 10)) fail(`${k} must be a number of seconds between 0 and 10`);
|
|
212
|
+
}
|
|
213
|
+
if (!(cfg.loudness <= -8 && cfg.loudness >= -30)) fail('loudness must be between -30 and -8 LUFS');
|
|
214
|
+
if (!(cfg.boil >= 0 && cfg.boil <= 12)) fail('boil must be between 0 (off) and 12 redraws per second');
|
|
215
|
+
if (cfg.watermark !== false && !(typeof cfg.watermark === 'string' && cfg.watermark.trim() && cfg.watermark.length <= 40)) {
|
|
216
|
+
fail('watermark must be false or a short text of up to 40 characters, like "example.com"');
|
|
217
|
+
}
|
|
218
|
+
if (cfg.images !== null) {
|
|
219
|
+
if (typeof cfg.images !== 'object' || Array.isArray(cfg.images)) fail('images must be an object like { "model": "best", "style": "..." }');
|
|
220
|
+
const extra = Object.keys(cfg.images).filter((k) => !['model', 'style'].includes(k));
|
|
221
|
+
if (extra.length) fail(`images has unknown setting(s): ${extra.join(', ')}. Known: model, style`);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
if (cfg.brand !== null) {
|
|
225
|
+
if (typeof cfg.brand !== 'object' || Array.isArray(cfg.brand)) fail('brand must be an object like { "accent": "#2563eb", "logo": "assets/logo.svg" }');
|
|
226
|
+
const extra = Object.keys(cfg.brand).filter((k) => !BRAND_KEYS.includes(k));
|
|
227
|
+
if (extra.length) fail(`brand has unknown setting(s): ${extra.join(', ')}. Known: ${BRAND_KEYS.join(', ')}`);
|
|
228
|
+
for (const k of ['accent', 'background', 'ink']) {
|
|
229
|
+
if (cfg.brand[k] !== undefined && !HEX.test(cfg.brand[k])) fail(`brand.${k} must be a color like "#2563eb", not ${JSON.stringify(cfg.brand[k])}`);
|
|
230
|
+
}
|
|
231
|
+
for (const k of ['font', 'headline']) {
|
|
232
|
+
if (cfg.brand[k] !== undefined && !(typeof cfg.brand[k] === 'string' && cfg.brand[k].trim())) fail(`brand.${k} must be a font family name, like "Inter"`);
|
|
233
|
+
}
|
|
234
|
+
if (cfg.brand.colors !== undefined) {
|
|
235
|
+
const c = cfg.brand.colors;
|
|
236
|
+
if (!c || typeof c !== 'object' || Array.isArray(c)) fail(`brand.colors must be an object like { "text": "#141413", "line": "#e8e6dc" }`);
|
|
237
|
+
for (const [k, v] of Object.entries(c)) {
|
|
238
|
+
if (!BRAND_COLORS.includes(k)) fail(`brand.colors has an unknown color "${k}". Known: ${BRAND_COLORS.join(', ')}`);
|
|
239
|
+
if (!HEX.test(v)) fail(`brand.colors.${k} must be a color like "#141413", not ${JSON.stringify(v)}`);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
if (cfg.brand.logo !== undefined && !(typeof cfg.brand.logo === 'string' && /^assets\/.+\.(svg|png|webp|jpe?g)$/i.test(cfg.brand.logo))) {
|
|
243
|
+
fail('brand.logo must be an image in the assets/ folder, like "assets/logo.svg"');
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
if (!Array.isArray(cfg.fonts)) fail('fonts must be a list like [{ "family": "Figtree", "src": "assets/fonts/figtree-600.woff2", "weight": 600 }]');
|
|
247
|
+
cfg.fonts.forEach((f, i) => {
|
|
248
|
+
const where = `fonts[${i}]`;
|
|
249
|
+
if (!f || typeof f !== 'object' || Array.isArray(f)) fail(`${where} must be an object with family and src`);
|
|
250
|
+
const extra = Object.keys(f).filter((k) => !['family', 'src', 'weight', 'style'].includes(k));
|
|
251
|
+
if (extra.length) fail(`${where} has unknown setting(s): ${extra.join(', ')}. Known: family, src, weight, style`);
|
|
252
|
+
if (!(typeof f.family === 'string' && f.family.trim())) fail(`${where}.family must be a font family name`);
|
|
253
|
+
if (!(typeof f.src === 'string' && f.src.startsWith('assets/') && FONT_FILE.test(f.src) && !f.src.split('/').includes('..'))) {
|
|
254
|
+
fail(`${where}.src must be a font file in the assets/ folder (.woff2, .woff, .ttf or .otf), like "assets/fonts/figtree-600.woff2"`);
|
|
255
|
+
}
|
|
256
|
+
const w = f.weight ?? 400;
|
|
257
|
+
const range = typeof w === 'string' ? w.split(/\s+/).map(Number) : [w];
|
|
258
|
+
if (!(range.length <= 2 && range.every((x) => Number.isInteger(x) && x >= 1 && x <= 1000))) fail(`${where}.weight must be a number like 600, or a range like "100 900" for a variable font`);
|
|
259
|
+
if (f.style !== undefined && !['normal', 'italic'].includes(f.style)) fail(`${where}.style must be "normal" or "italic"`);
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
if (lookPath(cfg.theme)) cfg.look = loadLook(dir, cfg.theme, cfg.fonts);
|
|
263
|
+
let music = cfg.music;
|
|
264
|
+
if (music === true) music = { style: cfg.look ? (cfg.look.music ?? THEME_MUSIC[cfg.look.extends]) : THEME_MUSIC[cfg.theme] };
|
|
265
|
+
else if (typeof music === 'string') music = { style: music };
|
|
266
|
+
if (music) {
|
|
267
|
+
// A faster pace plays the music a little faster too.
|
|
268
|
+
music = { volume: 0.5, seed: cfg.seed, tempo: Math.sqrt(cfg.pace), ...music };
|
|
269
|
+
if (!MUSIC_STYLES.includes(music.style)) fail(`music style must be one of ${MUSIC_STYLES.join(', ')}, not "${music.style}"`);
|
|
270
|
+
if (!(music.volume >= 0 && music.volume <= 1)) fail('music.volume must be between 0 and 1');
|
|
271
|
+
}
|
|
272
|
+
cfg.music = music || null;
|
|
273
|
+
|
|
274
|
+
const { width, height, safe } = resolveSize(cfg.size);
|
|
275
|
+
cfg.width = width;
|
|
276
|
+
cfg.height = height;
|
|
277
|
+
cfg.format = FORMATS[cfg.size] ? cfg.size : null;
|
|
278
|
+
cfg.safe = safe || null;
|
|
279
|
+
if (cfg.captions === 'auto') cfg.captions = height >= width;
|
|
280
|
+
return cfg;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export function findProjectDir(arg) {
|
|
284
|
+
const dir = path.resolve(arg || '.');
|
|
285
|
+
if (fs.existsSync(path.join(dir, 'video.json'))) return dir;
|
|
286
|
+
if (arg) fail(`${dir} is not a video project (no video.json). Create one with "explainroo init ${arg}".`);
|
|
287
|
+
fail('no video.json here. Run the command in a video folder or pass the project folder, for example "explainroo <command> videos/my-video".');
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export function loadProject(arg, { size } = {}) {
|
|
291
|
+
const dir = findProjectDir(arg);
|
|
292
|
+
let raw;
|
|
293
|
+
try {
|
|
294
|
+
raw = JSON.parse(fs.readFileSync(path.join(dir, 'video.json'), 'utf8'));
|
|
295
|
+
} catch (e) {
|
|
296
|
+
fail(`video.json is not valid JSON: ${e.message}`);
|
|
297
|
+
}
|
|
298
|
+
const config = normalizeConfig(size === undefined ? raw : { ...raw, size }, dir);
|
|
299
|
+
for (const f of [...config.fonts.map((x) => x.src), ...(config.brand?.logo ? [config.brand.logo] : [])]) {
|
|
300
|
+
if (!fs.existsSync(path.join(dir, f))) fail(`${f} is listed in video.json but the file is missing`);
|
|
301
|
+
}
|
|
302
|
+
const scriptPath = path.join(dir, 'script.md');
|
|
303
|
+
if (!fs.existsSync(scriptPath)) fail(`${scriptPath} is missing`);
|
|
304
|
+
const script = parseScript(fs.readFileSync(scriptPath, 'utf8'), { language: config.language });
|
|
305
|
+
if (!config.title) config.title = script.title || path.basename(dir);
|
|
306
|
+
const scenesPath = path.join(dir, 'scenes.js');
|
|
307
|
+
if (!fs.existsSync(scenesPath)) fail(`${scenesPath} is missing`);
|
|
308
|
+
const build = path.join(dir, 'build');
|
|
309
|
+
const out = path.join(dir, 'out');
|
|
310
|
+
return { dir, config, script, sizeOverride: size, paths: { build, out, voice: path.join(build, 'voice'), scenes: scenesPath, script: scriptPath, look: config.look ? path.resolve(dir, config.theme) : null } };
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
export function outputPath(project, name, ext = '', out = null) {
|
|
314
|
+
const suffix = project.sizeOverride === undefined ? '' : `-${project.sizeOverride.replace(':', '-')}`;
|
|
315
|
+
return path.resolve(out || path.join(project.paths.out, `${name}${suffix}${ext}`));
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export function listAssets(dir) {
|
|
319
|
+
const root = path.join(dir, 'assets');
|
|
320
|
+
if (!fs.existsSync(root)) return [];
|
|
321
|
+
const out = [];
|
|
322
|
+
const walk = (d) => {
|
|
323
|
+
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
|
|
324
|
+
const p = path.join(d, e.name);
|
|
325
|
+
if (e.isDirectory()) walk(p);
|
|
326
|
+
else out.push(path.relative(dir, p).split(path.sep).join('/'));
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
walk(root);
|
|
330
|
+
return out.sort();
|
|
331
|
+
}
|
package/engine/src/qa.js
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
// Quality tools for the agent: layout checks, stills, contact sheets and a
|
|
2
|
+
// verification pass over the rendered video.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { prepare, withEngine } from './pipeline.js';
|
|
6
|
+
import { probe, loudness, ffmpeg } from './ffmpeg.js';
|
|
7
|
+
import { transcribeWords } from './models.js';
|
|
8
|
+
import { readWav } from './wav.js';
|
|
9
|
+
import { alignWords, readAlike } from './align.js';
|
|
10
|
+
import { buildChapters, chapterHints } from './chapters.js';
|
|
11
|
+
import { outputPath } from './project.js';
|
|
12
|
+
|
|
13
|
+
export async function check(project, { log = () => {}, step = 0.25, viewWidth = null } = {}) {
|
|
14
|
+
if (viewWidth !== null && (!Number.isFinite(viewWidth) || viewWidth <= 0)) throw new Error("--view-width must be a positive number");
|
|
15
|
+
const { voices, timeline } = await prepare(project, { log });
|
|
16
|
+
const issues = chapterHints(buildChapters(timeline, project.script.title || project.config.title));
|
|
17
|
+
for (const sc of project.script.scenes) {
|
|
18
|
+
const v = voices[sc.id];
|
|
19
|
+
const suspicious = v ? v.unmatched.filter((w) => w.replace(/[^\p{L}\p{M}\p{N}]/gu, '').length > 3) : [];
|
|
20
|
+
if (v && v.duration && (v.matchRate < 0.9 || suspicious.length)) {
|
|
21
|
+
issues.push({ level: 'warn', scene: sc.id, t: null, message: `the voice check could not confirm ${suspicious.length ? suspicious.slice(0, 8).map((w) => `"${w}"`).join(', ') : `${Math.round((1 - v.matchRate) * 100)}% of the words`}. It heard: "${v.transcript.slice(0, 200)}". ${project.config.voice.provider === 'recording' ? 'The recording does not match script.md here. Make script.md say what was actually said.' : 'If a word is mispronounced, write it as {shown|spoken} in script.md.'}` });
|
|
22
|
+
}
|
|
23
|
+
if (v && v.duration > 40) issues.push({ level: 'hint', scene: sc.id, t: null, message: `the narration runs ${v.duration.toFixed(0)}s; long scenes are easier to follow when split` });
|
|
24
|
+
}
|
|
25
|
+
const pageIssues = await withEngine(project, timeline, { scale: 0.5, log }, (page) => page.evaluate(([s, w]) => window.explainroo.check(s, w), [step, viewWidth]));
|
|
26
|
+
issues.push(...pageIssues);
|
|
27
|
+
const order = { error: 0, warn: 1, hint: 2 };
|
|
28
|
+
issues.sort((a, b) => order[a.level] - order[b.level]);
|
|
29
|
+
return { issues, duration: timeline.duration, scenes: timeline.scenes.length };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Specs: "12.5" (seconds into the video), "scene" (end of the scene, when it
|
|
33
|
+
// is fully built), "scene@2.4" (seconds into the scene), "scene@end".
|
|
34
|
+
export function resolveTimes(timeline, specs) {
|
|
35
|
+
const byId = new Map(timeline.scenes.map((s) => [s.id, s]));
|
|
36
|
+
const endOf = (sc) => sc.start + Math.max(0, sc.dur - 0.3);
|
|
37
|
+
if (!specs.length) return timeline.scenes.map((sc) => ({ T: endOf(sc), label: `${sc.id}@end` }));
|
|
38
|
+
return specs.map((spec) => {
|
|
39
|
+
if (typeof spec === 'number' || /^\d+(\.\d+)?$/.test(spec)) {
|
|
40
|
+
const T = Math.min(Number(spec), timeline.duration - 1 / timeline.fps);
|
|
41
|
+
return { T, label: `t${T.toFixed(2)}` };
|
|
42
|
+
}
|
|
43
|
+
const [id, at] = spec.split('@');
|
|
44
|
+
const sc = byId.get(id);
|
|
45
|
+
if (!sc) throw new Error(`no scene "${id}". Scenes: ${[...byId.keys()].join(', ')}`);
|
|
46
|
+
if (!at || at === 'end') return { T: endOf(sc), label: `${id}@end` };
|
|
47
|
+
if (at === 'start') return { T: sc.start, label: `${id}@start` };
|
|
48
|
+
const local = Number(at);
|
|
49
|
+
if (!Number.isFinite(local)) throw new Error(`"${spec}": use scene@seconds, for example ${id}@1.5`);
|
|
50
|
+
// Keep the time as written, so "ask@7.0" saves as ask@7.0.png.
|
|
51
|
+
return { T: sc.start + Math.min(local, sc.dur - 0.01), label: `${id}@${at}` };
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function stills(project, specs, { log = () => {}, scale = 1, transparent = false } = {}) {
|
|
56
|
+
const { timeline } = await prepare(project, { log });
|
|
57
|
+
const dir = path.relative(project.dir, outputPath(project, 'stills')).split(path.sep).join('/');
|
|
58
|
+
const list = resolveTimes(timeline, specs).map((x) => ({ ...x, path: `${dir}/${x.label.replace(/[^\w@.-]/g, '_')}.png` }));
|
|
59
|
+
await withEngine(project, timeline, { scale, transparent, log }, (page) => page.evaluate((l) => window.explainroo.stills(l), list));
|
|
60
|
+
return list.map((x) => ({ time: Math.round(x.T * 100) / 100, label: x.label, file: path.join(project.dir, x.path) }));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function sheet(project, { scene = null, every = null, cols = null, log = () => {} } = {}) {
|
|
64
|
+
const { timeline } = await prepare(project, { log });
|
|
65
|
+
let times = [];
|
|
66
|
+
let labels = [];
|
|
67
|
+
const file = path.relative(project.dir, outputPath(project, scene ? `sheet-${scene}` : 'sheet', '.jpg')).split(path.sep).join('/');
|
|
68
|
+
if (scene) {
|
|
69
|
+
const sc = timeline.scenes.find((s) => s.id === scene);
|
|
70
|
+
if (!sc) throw new Error(`no scene "${scene}". Scenes: ${timeline.scenes.map((s) => s.id).join(', ')}`);
|
|
71
|
+
const step = every ?? Math.max(0.25, Math.min(1, sc.dur / 16));
|
|
72
|
+
for (let t = 0; t < sc.dur - 0.01; t += step) {
|
|
73
|
+
times.push(sc.start + t);
|
|
74
|
+
labels.push(`${sc.id} ${t.toFixed(2)}s`);
|
|
75
|
+
}
|
|
76
|
+
times.push(sc.start + sc.dur - 0.05);
|
|
77
|
+
labels.push(`${sc.id} end`);
|
|
78
|
+
} else {
|
|
79
|
+
const step = every ?? Math.max(0.5, Math.min(3, timeline.duration / 30));
|
|
80
|
+
for (let T = 0; T < timeline.duration; T += step) {
|
|
81
|
+
const sc = [...timeline.scenes].reverse().find((s) => T >= s.start) || timeline.scenes[0];
|
|
82
|
+
times.push(T);
|
|
83
|
+
labels.push(`${sc.id} ${(T - sc.start).toFixed(1)}s`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const c = cols ?? (times.length > 20 ? 6 : times.length > 9 ? 5 : 4);
|
|
87
|
+
const thumb = timeline.width >= timeline.height ? 320 : 200;
|
|
88
|
+
await withEngine(project, timeline, { scale: 0.5, log }, (page) => page.evaluate((o) => window.explainroo.sheet(o), { times, labels, cols: c, thumb, path: file }));
|
|
89
|
+
return { file: path.join(project.dir, file), frames: times.length };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function verify(project, { file = null, log = () => {} } = {}) {
|
|
93
|
+
const video = path.resolve(file || path.join(project.paths.out, 'video.mp4'));
|
|
94
|
+
if (path.extname(video).toLowerCase() === '.gif') throw new Error('verify checks MP4, WebM and MOV files. Pass a video with --file.');
|
|
95
|
+
if (!fs.existsSync(video)) throw new Error(`${video} does not exist. Run "explainroo render" first.`);
|
|
96
|
+
const issues = [];
|
|
97
|
+
const info = await probe(video);
|
|
98
|
+
const v = info.streams.find((s) => s.codec_type === 'video');
|
|
99
|
+
const a = info.streams.find((s) => s.codec_type === 'audio');
|
|
100
|
+
const duration = Number(info.format.duration);
|
|
101
|
+
if (!v) issues.push({ level: 'error', message: 'the file has no video stream' });
|
|
102
|
+
if (!a) issues.push({ level: 'error', message: 'the file has no audio stream' });
|
|
103
|
+
const loud = a ? await loudness(video) : null;
|
|
104
|
+
if (loud && loud.integrated !== null && Math.abs(loud.integrated - project.config.loudness) > 1.5) {
|
|
105
|
+
issues.push({ level: 'warn', message: `loudness is ${loud.integrated} LUFS, target is ${project.config.loudness}` });
|
|
106
|
+
}
|
|
107
|
+
if (loud && loud.truePeak !== null && loud.truePeak > -0.5) issues.push({ level: 'warn', message: `true peak ${loud.truePeak} dBFS is close to clipping` });
|
|
108
|
+
|
|
109
|
+
const alpha = v && (String(v.tags?.alpha_mode ?? v.tags?.ALPHA_MODE) === '1' || /^(yuva|rgba|bgra|gbrap|argb|abgr)/.test(v.pix_fmt || ''));
|
|
110
|
+
let blacks = [];
|
|
111
|
+
if (alpha) issues.push({ level: 'hint', message: 'black-frame detection is skipped because the video has alpha' });
|
|
112
|
+
else if (v) {
|
|
113
|
+
const { stderr: bd } = await ffmpeg(['-nostats', '-i', video, '-vf', 'blackdetect=d=0.4:pix_th=0.08', '-an', '-f', 'null', '-']);
|
|
114
|
+
blacks = [...bd.matchAll(/black_start:([\d.]+) black_end:([\d.]+)/g)].map((m) => [Number(m[1]), Number(m[2])]);
|
|
115
|
+
}
|
|
116
|
+
for (const [s, e] of blacks) issues.push({ level: 'warn', message: `black frames from ${s.toFixed(2)}s to ${e.toFixed(2)}s` });
|
|
117
|
+
|
|
118
|
+
let silences = [];
|
|
119
|
+
if (a) {
|
|
120
|
+
const { stderr: sd } = await ffmpeg(['-nostats', '-i', video, '-af', 'silencedetect=n=-50dB:d=2.5', '-vn', '-f', 'null', '-']);
|
|
121
|
+
const starts = [...sd.matchAll(/silence_start: ([\d.]+)/g)].map((m) => Number(m[1]));
|
|
122
|
+
const ends = [...sd.matchAll(/silence_end: ([\d.]+)/g)].map((m) => Number(m[1]));
|
|
123
|
+
silences = starts.map((s, i) => [s, ends[i] ?? duration]);
|
|
124
|
+
for (const [s, e] of silences) issues.push({ level: 'hint', message: `near silence from ${s.toFixed(1)}s to ${e.toFixed(1)}s` });
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Can the narration be understood over the music and effects? Each scene
|
|
128
|
+
// is transcribed on its own: Whisper sometimes drops a whole 30 second
|
|
129
|
+
// chunk of a long file ("(bell dings)"), and per scene the report can say
|
|
130
|
+
// where the voice is hard to follow.
|
|
131
|
+
let speech = null;
|
|
132
|
+
if (a) {
|
|
133
|
+
const wav = path.join(project.paths.build, 'verify-16k.wav');
|
|
134
|
+
await ffmpeg(['-loglevel', 'error', '-i', video, '-vn', '-ac', '1', '-ar', '16000', '-c:a', 'pcm_s16le', wav]);
|
|
135
|
+
const { samples } = readWav(wav);
|
|
136
|
+
log('checking that the narration is understandable in the final mix');
|
|
137
|
+
const tlFile = path.join(project.paths.build, 'timeline.json');
|
|
138
|
+
const timeline = fs.existsSync(tlFile) ? JSON.parse(fs.readFileSync(tlFile, 'utf8')) : null;
|
|
139
|
+
const spokenWords = (sc) => sc.units.filter((u) => u.type === 'word').map((u) => ({ spoken: u.spoken, display: u.display }));
|
|
140
|
+
const byId = new Map(project.script.scenes.map((sc) => [sc.id, sc]));
|
|
141
|
+
const sameScenes = timeline && timeline.scenes.length === project.script.scenes.length && timeline.scenes.every((t) => byId.has(t.id)) && Math.abs(timeline.duration - duration) < 1;
|
|
142
|
+
if (sameScenes) {
|
|
143
|
+
const texts = [];
|
|
144
|
+
const scenes = [];
|
|
145
|
+
let total = 0;
|
|
146
|
+
let matched = 0;
|
|
147
|
+
for (const t of timeline.scenes) {
|
|
148
|
+
const words = spokenWords(byId.get(t.id));
|
|
149
|
+
if (!words.length) continue;
|
|
150
|
+
const from = Math.max(0, Math.floor(t.start * 16000));
|
|
151
|
+
const to = Math.min(samples.length, Math.ceil((t.start + t.dur) * 16000));
|
|
152
|
+
const heard = await transcribeWords(samples.subarray(from, to), { log, language: project.config.language });
|
|
153
|
+
texts.push(heard.text);
|
|
154
|
+
const alike = await readAlike(words, heard.words, project.config.language);
|
|
155
|
+
const rate = alignWords(alike.words, alike.heard, t.dur, project.config.language).matchRate;
|
|
156
|
+
scenes.push({ id: t.id, matchRate: Math.round(rate * 1000) / 1000 });
|
|
157
|
+
total += words.length;
|
|
158
|
+
matched += rate * words.length;
|
|
159
|
+
if (rate < 0.8) issues.push({ level: 'warn', message: `scene "${t.id}": only ${Math.round(rate * 100)}% of the narration was understood in the final mix; it heard "${heard.text.slice(0, 120)}"` });
|
|
160
|
+
}
|
|
161
|
+
const rate = total ? matched / total : 1;
|
|
162
|
+
speech = { matchRate: Math.round(rate * 1000) / 1000, transcript: texts.join(' '), scenes };
|
|
163
|
+
} else {
|
|
164
|
+
const heard = await transcribeWords(samples, { log, language: project.config.language });
|
|
165
|
+
const script = project.script.scenes.flatMap(spokenWords);
|
|
166
|
+
const alike = await readAlike(script, heard.words, project.config.language);
|
|
167
|
+
speech = { matchRate: Math.round(alignWords(alike.words, alike.heard, duration, project.config.language).matchRate * 1000) / 1000, transcript: heard.text };
|
|
168
|
+
}
|
|
169
|
+
if (speech.matchRate < 0.85) issues.push({ level: 'warn', message: `only ${Math.round(speech.matchRate * 100)}% of the script was understood in the final mix; lower music.volume or check pronunciation` });
|
|
170
|
+
fs.rmSync(wav, { force: true });
|
|
171
|
+
}
|
|
172
|
+
const report = {
|
|
173
|
+
file: video,
|
|
174
|
+
duration: Math.round(duration * 100) / 100,
|
|
175
|
+
video: v ? { width: v.width, height: v.height, fps: v.r_frame_rate, codec: v.codec_name } : null,
|
|
176
|
+
audio: a ? { codec: a.codec_name, sampleRate: Number(a.sample_rate), channels: a.channels } : null,
|
|
177
|
+
loudness: loud,
|
|
178
|
+
blackSegments: blacks,
|
|
179
|
+
silences,
|
|
180
|
+
speech,
|
|
181
|
+
issues,
|
|
182
|
+
};
|
|
183
|
+
fs.mkdirSync(project.paths.out, { recursive: true });
|
|
184
|
+
fs.writeFileSync(path.join(project.paths.out, 'report.json'), JSON.stringify(report, null, 2));
|
|
185
|
+
return report;
|
|
186
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import { ProjectError } from './project.js';
|
|
5
|
+
import { alignWords } from './align.js';
|
|
6
|
+
import { ffmpeg, probe, normalizeLoudness } from './ffmpeg.js';
|
|
7
|
+
import { readWav, writeWav } from './wav.js';
|
|
8
|
+
|
|
9
|
+
const AUDIO_FILE = /\.(wav|mp3|m4a|aac|flac|ogg|opus)$/i;
|
|
10
|
+
// Four Kokoro scenes from how-dns-works measured -22.0 to -22.5 LUFS.
|
|
11
|
+
const RECORDING_LUFS = -22.3;
|
|
12
|
+
|
|
13
|
+
export function recordingFiles(project) {
|
|
14
|
+
const src = project.config.voice.src;
|
|
15
|
+
const file = path.join(project.dir, src);
|
|
16
|
+
const assets = path.join(fs.realpathSync(project.dir), 'assets');
|
|
17
|
+
const inside = (p) => fs.realpathSync(p).startsWith(assets + path.sep);
|
|
18
|
+
if (!fs.existsSync(file)) throw new ProjectError(`${src} is missing. Put the recording in assets/ and check voice.src.`);
|
|
19
|
+
if (!inside(file)) throw new ProjectError('recordings must stay inside assets/, including symlinks');
|
|
20
|
+
const folder = fs.statSync(file).isDirectory();
|
|
21
|
+
if (!folder && !AUDIO_FILE.test(file)) throw new ProjectError('recordings must be wav, mp3, m4a, aac, flac, ogg or opus files');
|
|
22
|
+
const files = {};
|
|
23
|
+
const hashes = new Map();
|
|
24
|
+
const missing = [];
|
|
25
|
+
const names = folder ? fs.readdirSync(file).sort() : [];
|
|
26
|
+
for (const scene of project.script.scenes) {
|
|
27
|
+
if (!scene.units.some((u) => u.type === 'word')) continue;
|
|
28
|
+
const name = names.find((n) => path.parse(n).name === scene.id && AUDIO_FILE.test(n) && fs.existsSync(path.join(file, n)) && fs.statSync(path.join(file, n)).isFile());
|
|
29
|
+
if (folder && !name) { missing.push(scene.id); continue; }
|
|
30
|
+
const p = folder ? path.join(file, name) : file;
|
|
31
|
+
if (!inside(p)) throw new ProjectError('recordings must stay inside assets/, including symlinks');
|
|
32
|
+
if (!hashes.has(p)) hashes.set(p, crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex'));
|
|
33
|
+
files[scene.id] = { file: p, hash: hashes.get(p) };
|
|
34
|
+
}
|
|
35
|
+
if (missing.length) throw new ProjectError(`missing scene recordings in ${src}: ${missing.join(', ')}. Add <scene-id>.<ext> for each scene with narration.`);
|
|
36
|
+
return { folder, files };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function tempo(speed) {
|
|
40
|
+
const filters = [];
|
|
41
|
+
while (speed < 0.5) { filters.push('atempo=0.5'); speed /= 0.5; }
|
|
42
|
+
while (speed > 2) { filters.push('atempo=2'); speed /= 2; }
|
|
43
|
+
if (speed !== 1) filters.push(`atempo=${speed}`);
|
|
44
|
+
return filters;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function decodeRecording(file, build, speed) {
|
|
48
|
+
const info = await probe(file);
|
|
49
|
+
const stream = info.streams.find((s) => s.codec_type === 'audio');
|
|
50
|
+
if (!stream) throw new ProjectError('the recording has no audio. Choose an audio file in voice.src.');
|
|
51
|
+
const sampleRate = Math.min(48000, Number(stream.sample_rate));
|
|
52
|
+
const dir = fs.mkdtempSync(path.join(build, 'recording-'));
|
|
53
|
+
try {
|
|
54
|
+
const wav = path.join(dir, 'decoded.wav');
|
|
55
|
+
const filters = tempo(speed);
|
|
56
|
+
await ffmpeg(['-loglevel', 'error', '-i', file, '-vn', '-ac', '1', '-ar', String(sampleRate),
|
|
57
|
+
...(filters.length ? ['-af', filters.join(',')] : []), '-c:a', 'pcm_s16le', wav]);
|
|
58
|
+
return readWav(wav);
|
|
59
|
+
} finally {
|
|
60
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function saveRecording(file, samples, sampleRate) {
|
|
65
|
+
const dir = fs.mkdtempSync(path.join(path.dirname(file), 'recording-'));
|
|
66
|
+
try {
|
|
67
|
+
const input = path.join(dir, 'input.wav');
|
|
68
|
+
writeWav(input, samples, sampleRate);
|
|
69
|
+
await normalizeLoudness(input, file, RECORDING_LUFS, sampleRate);
|
|
70
|
+
} finally {
|
|
71
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function recordingCuts(scenes, heard, duration, language = 'en') {
|
|
76
|
+
const spoken = scenes.map((scene) => ({ scene, words: scene.units.filter((u) => u.type === 'word') })).filter((s) => s.words.length);
|
|
77
|
+
const aligned = alignWords(spoken.flatMap((s) => s.words), heard, duration, language).words;
|
|
78
|
+
let offset = 0;
|
|
79
|
+
const spans = spoken.map(({ scene, words }) => {
|
|
80
|
+
const times = aligned.slice(offset, offset + words.length);
|
|
81
|
+
offset += words.length;
|
|
82
|
+
return { scene, words: times, first: times[0].start, last: times.at(-1).end };
|
|
83
|
+
});
|
|
84
|
+
return spans.map((s, i) => {
|
|
85
|
+
const left = i ? (spans[i - 1].last + s.first) / 2 : 0;
|
|
86
|
+
const right = i + 1 < spans.length ? (s.last + spans[i + 1].first) / 2 : duration;
|
|
87
|
+
return { scene: s.scene, words: s.words, start: Math.max(0, left, s.first - 0.15), end: Math.min(duration, right, s.last + 0.15) };
|
|
88
|
+
});
|
|
89
|
+
}
|