@biunow/agent-biutalk 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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,187 @@
|
|
|
1
|
+
// A static player uses the same frames and mix as a render, without a server.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { cacheRoot } from './models.js';
|
|
6
|
+
import { languageFonts, subsetFont } from './fonts.js';
|
|
7
|
+
import { prepare, makeState } from './pipeline.js';
|
|
8
|
+
import { startServer, projectFile, ROOT } from './server.js';
|
|
9
|
+
import { launch, openEngine } from './browser.js';
|
|
10
|
+
import { ffmpeg, normalizeLoudness } from './ffmpeg.js';
|
|
11
|
+
import { resolveTimes } from './qa.js';
|
|
12
|
+
import { subtitleCues, toVtt } from './subtitles.js';
|
|
13
|
+
|
|
14
|
+
export function localModules(dir, entry = 'scenes.js') {
|
|
15
|
+
const files = new Map();
|
|
16
|
+
const visit = rel => {
|
|
17
|
+
if (files.has(rel)) return;
|
|
18
|
+
const file = projectFile(dir, rel);
|
|
19
|
+
if (!file || !/\.m?js$/i.test(file)) throw new Error(`module "${rel}" cannot be exported. Keep modules inside the project, away from dotfiles.`);
|
|
20
|
+
const source = fs.readFileSync(file, 'utf8');
|
|
21
|
+
files.set(rel, file);
|
|
22
|
+
const imports = /\/\/[^\n]*|\/\*[\s\S]*?\*\/|'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`(?:\\.|[^`\\])*`|\b(?:import|export)\s+(?:[\w\s,*{}$]+\s+from\s*)?['"]([^'"\n]+)['"]|\bimport\s*\(\s*['"]([^'"\n]+)['"]\s*\)/g;
|
|
23
|
+
for (const m of source.matchAll(imports)) {
|
|
24
|
+
const spec = m[1] || m[2];
|
|
25
|
+
if (!spec) continue;
|
|
26
|
+
if (!spec.startsWith('./') && !spec.startsWith('../')) throw new Error(`module "${spec}" cannot be exported. Use a relative local import.`);
|
|
27
|
+
visit(path.posix.normalize(path.posix.join(path.posix.dirname(rel), spec.split(/[?#]/)[0])));
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
visit(entry);
|
|
31
|
+
return files;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function copyPlayer(project, timeline, used, out) {
|
|
35
|
+
const copy = (src, rel) => {
|
|
36
|
+
const dest = path.join(out, rel);
|
|
37
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
38
|
+
fs.copyFileSync(src, dest);
|
|
39
|
+
};
|
|
40
|
+
const projectModules = localModules(project.dir);
|
|
41
|
+
for (const rel of used.modules || []) for (const [name, file] of localModules(project.dir, rel)) projectModules.set(name, file);
|
|
42
|
+
for (const [rel, file] of projectModules) copy(file, `project/${rel}`);
|
|
43
|
+
for (const rel of used.assets) {
|
|
44
|
+
const file = projectFile(project.dir, rel);
|
|
45
|
+
if (!file || !rel.startsWith('assets/')) throw new Error(`asset "${rel}" cannot be exported. Keep assets inside assets/, away from dotfiles.`);
|
|
46
|
+
if (/\.svg$/i.test(rel) && /(?:href\s*=\s*['"]|url\(\s*['"]?)(?:\/|[a-z]+:)/i.test(fs.readFileSync(file, 'utf8'))) throw new Error(`image "${rel}" uses an outside file. Use a self-contained image.`);
|
|
47
|
+
copy(file, `project/${rel}`);
|
|
48
|
+
}
|
|
49
|
+
const text = (used.text || '') + timeline.scenes.flatMap(s => s.words.map(w => w.text)).join('');
|
|
50
|
+
// Every font string names the Hindi fallback, but only Hindi text needs it.
|
|
51
|
+
const fonts = JSON.parse(fs.readFileSync(path.join(ROOT, 'fonts/fonts.json'), 'utf8'))
|
|
52
|
+
.filter(f => used.fonts.includes(f.family) && (f.family !== 'Noto Sans Devanagari' || /\p{Script=Devanagari}/u.test(text)));
|
|
53
|
+
for (const f of fonts) copy(path.join(ROOT, 'fonts', f.file), `fonts/${f.file}`);
|
|
54
|
+
for (const family of new Set(fonts.map(f => f.family))) {
|
|
55
|
+
const name = family.replaceAll(' ', '') + '-OFL.txt';
|
|
56
|
+
copy(path.join(ROOT, 'fonts/licenses', name), `fonts/licenses/${name}`);
|
|
57
|
+
}
|
|
58
|
+
fs.mkdirSync(path.join(out, 'fonts'), { recursive: true });
|
|
59
|
+
// Japanese and Chinese fonts keep only the characters the video draws.
|
|
60
|
+
for (const f of languageFonts(project.config.language)) {
|
|
61
|
+
fs.writeFileSync(path.join(out, 'fonts', f.file), subsetFont(fs.readFileSync(f.path), text));
|
|
62
|
+
fonts.push({ family: f.family, weight: f.weight, file: f.file });
|
|
63
|
+
}
|
|
64
|
+
if (languageFonts(project.config.language).length) copy(path.join(cacheRoot(), 'fonts', 'NotoSansCJK-OFL.txt'), 'fonts/licenses/NotoSansCJK-OFL.txt');
|
|
65
|
+
fs.writeFileSync(path.join(out, 'fonts/fonts.json'), JSON.stringify(fonts));
|
|
66
|
+
// Audio synthesis and upload code run during export, never during playback.
|
|
67
|
+
const modules = ['runtime', 'stage', 'themes', 'pen', 'transitions', 'captions', 'util', 'layout', 'clips', 'ui', 'readability', 'pathdata', 'text', 'code', 'director'];
|
|
68
|
+
for (const name of modules) copy(path.join(ROOT, 'engine', `${name}.js`), `engine/${name}.js`);
|
|
69
|
+
copy(path.join(ROOT, 'engine/icons/lucide.json'), 'engine/icons/lucide.json');
|
|
70
|
+
copy(path.join(ROOT, 'engine/icons/LICENSE-lucide.txt'), 'engine/icons/LICENSE-lucide.txt');
|
|
71
|
+
const rough = fileURLToPath(import.meta.resolve('roughjs/bundled/rough.esm.js'));
|
|
72
|
+
copy(rough, 'vendor/rough.js');
|
|
73
|
+
copy(path.join(path.dirname(rough), '../LICENSE'), 'vendor/LICENSE-roughjs.txt');
|
|
74
|
+
copy(path.join(ROOT, 'LICENSE'), 'LICENSE');
|
|
75
|
+
copy(path.join(ROOT, 'engine/player.html'), 'index.html');
|
|
76
|
+
copy(path.join(ROOT, 'engine/player.js'), 'engine/player.js');
|
|
77
|
+
const state = makeState(project, timeline);
|
|
78
|
+
state.config = Object.fromEntries(Object.entries(state.config).filter(([key]) => !key.startsWith('_') && key !== 'images'));
|
|
79
|
+
state.config.fonts = state.config.fonts.filter(f => used.assets.includes(f.src));
|
|
80
|
+
if (state.config.brand?.logo && !used.assets.includes(state.config.brand.logo)) {
|
|
81
|
+
state.config.brand = { ...state.config.brand };
|
|
82
|
+
delete state.config.brand.logo;
|
|
83
|
+
}
|
|
84
|
+
// A custom look is already resolved in config.look; its source is private.
|
|
85
|
+
if (state.config.look) state.config.theme = state.config.look.extends;
|
|
86
|
+
if (typeof state.config.voice === 'object' && state.config.voice.provider === 'recording') state.config.voice = { provider: 'recording', src: 'audio.m4a' };
|
|
87
|
+
state.timeline = { ...timeline, scenes: timeline.scenes.map(s => ({ ...s, voice: s.voice ? { ...s.voice, url: 'audio.m4a' } : null })) };
|
|
88
|
+
state.assets = used.assets.filter(a => !/\.(woff2?|ttf|otf)$/i.test(a));
|
|
89
|
+
fs.writeFileSync(path.join(out, 'state.json'), JSON.stringify(state));
|
|
90
|
+
fs.writeFileSync(path.join(out, 'math.json'), JSON.stringify(used.math));
|
|
91
|
+
fs.writeFileSync(path.join(out, 'subtitles.vtt'), toVtt(subtitleCues(timeline)));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function exportPlayer(project, { out, log = () => {} } = {}) {
|
|
95
|
+
out = path.resolve(out || path.join(project.paths.out, 'player'));
|
|
96
|
+
if (fs.existsSync(out) && fs.readdirSync(out).length && (!fs.existsSync(path.join(out, 'index.html')) || !fs.readFileSync(path.join(out, 'index.html'), 'utf8').includes('<meta name="generator" content="explainroo web player">'))) throw new Error('output folder is not an exported player. Choose an empty folder with --out.');
|
|
97
|
+
localModules(project.dir);
|
|
98
|
+
const { timeline } = await prepare(project, { log });
|
|
99
|
+
const state = makeState(project, timeline);
|
|
100
|
+
state.assets = state.assets.filter(a => projectFile(project.dir, a));
|
|
101
|
+
let browser, server;
|
|
102
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
103
|
+
const temp = fs.mkdtempSync(path.join(path.dirname(out), '.player-'));
|
|
104
|
+
try {
|
|
105
|
+
server = await startServer({ projectDir: project.dir, getState: () => state, log });
|
|
106
|
+
browser = await launch();
|
|
107
|
+
const context = await browser.newContext();
|
|
108
|
+
let outside;
|
|
109
|
+
const projectModules = new Set();
|
|
110
|
+
await context.route('**/*', route => {
|
|
111
|
+
const url = new URL(route.request().url());
|
|
112
|
+
if (url.origin !== server.url) {
|
|
113
|
+
outside = route.request().url();
|
|
114
|
+
return route.abort();
|
|
115
|
+
}
|
|
116
|
+
if (url.pathname.startsWith('/project/') && /\.m?js$/i.test(url.pathname)) projectModules.add(decodeURIComponent(url.pathname.slice(9)));
|
|
117
|
+
return route.continue();
|
|
118
|
+
});
|
|
119
|
+
// openEngine uses browser.newPage, so keep its requests in this context.
|
|
120
|
+
const page = await openEngine(context, server.url);
|
|
121
|
+
const cover = resolveTimes(timeline, [project.config.cover === 'auto' ? `${timeline.scenes[0].id}@end` : project.config.cover])[0].T;
|
|
122
|
+
const used = await page.evaluate(async cover => {
|
|
123
|
+
const { boot } = await import('/engine/runtime.js');
|
|
124
|
+
const { engine } = await boot({ canvas: document.createElement('canvas') });
|
|
125
|
+
const assets = new Set();
|
|
126
|
+
const fonts = new Set();
|
|
127
|
+
for (const method of ['image', 'clip']) {
|
|
128
|
+
const original = engine[method].bind(engine);
|
|
129
|
+
engine[method] = src => {
|
|
130
|
+
const result = original(src);
|
|
131
|
+
const key = src.replace(/^\.?\//, '');
|
|
132
|
+
assets.add(engine[method === 'image' ? 'images' : 'clips'].has(key) ? key : 'assets/' + key);
|
|
133
|
+
return result;
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
const proto = CanvasRenderingContext2D.prototype;
|
|
137
|
+
const font = Object.getOwnPropertyDescriptor(proto, 'font');
|
|
138
|
+
const chars = new Set();
|
|
139
|
+
const drawing = ['fillText', 'strokeText', 'measureText'].map(name => [name, proto[name]]);
|
|
140
|
+
for (const [name, original] of drawing) proto[name] = function (text, ...rest) {
|
|
141
|
+
for (const c of String(text)) chars.add(c);
|
|
142
|
+
return original.call(this, text, ...rest);
|
|
143
|
+
};
|
|
144
|
+
Object.defineProperty(proto, 'font', { ...font, set(value) {
|
|
145
|
+
for (const m of value.matchAll(/["']([^"']+)["']/g)) fonts.add(m[1]);
|
|
146
|
+
font.set.call(this, value);
|
|
147
|
+
} });
|
|
148
|
+
try {
|
|
149
|
+
const { renderAudio } = await import('/engine/runtime.js');
|
|
150
|
+
const audio = await import('/engine/audio/soundtrack.js');
|
|
151
|
+
const { upload } = await import('/engine/upload.js');
|
|
152
|
+
const sound = await renderAudio(engine, audio);
|
|
153
|
+
if (sound.errors.length) throw new Error(sound.errors[0].message);
|
|
154
|
+
// Music-free videos still need their scenes sampled for asset usage.
|
|
155
|
+
const collected = engine.collectEvents();
|
|
156
|
+
if (collected.errors.length) throw new Error(collected.errors[0].message);
|
|
157
|
+
for (const sc of engine.timeline.scenes) engine.renderFrame(sc.start + sc.dur - 1 / engine.fps);
|
|
158
|
+
await engine.prepareFrame(cover);
|
|
159
|
+
engine.renderFrame(cover, undefined, { captions: false });
|
|
160
|
+
await upload('build/player-mix.wav', audio.encodeWav(sound.buffer));
|
|
161
|
+
await upload('build/player-poster.jpg', await new Promise(resolve => engine.canvas.toBlob(resolve, 'image/jpeg', 0.9)));
|
|
162
|
+
if ([...engine.mathCache.values()].some(m => m?.error)) throw new Error('a formula could not be typeset. Run check and fix it before exporting.');
|
|
163
|
+
return { assets: [...assets], fonts: [...fonts], text: [...chars].join(''), math: Object.fromEntries(engine.mathCache) };
|
|
164
|
+
} finally {
|
|
165
|
+
Object.defineProperty(proto, 'font', font);
|
|
166
|
+
for (const [name, original] of drawing) proto[name] = original;
|
|
167
|
+
}
|
|
168
|
+
}, cover);
|
|
169
|
+
if (outside) throw new Error('the project uses an outside URL. Use local files before exporting.');
|
|
170
|
+
used.modules = [...projectModules];
|
|
171
|
+
for (const f of project.config.fonts) if (used.fonts.includes(f.family)) used.assets.push(f.src);
|
|
172
|
+
copyPlayer(project, timeline, used, temp);
|
|
173
|
+
const mix = path.join(project.paths.build, 'player-mix.wav');
|
|
174
|
+
const norm = path.join(project.paths.build, 'player-mix-norm.wav');
|
|
175
|
+
await normalizeLoudness(mix, norm, project.config.loudness);
|
|
176
|
+
await ffmpeg(['-loglevel', 'error', '-i', norm, '-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart', path.join(temp, 'audio.m4a')]);
|
|
177
|
+
fs.copyFileSync(path.join(project.paths.build, 'player-poster.jpg'), path.join(temp, 'poster.jpg'));
|
|
178
|
+
if (fs.existsSync(out)) fs.rmSync(out, { recursive: true });
|
|
179
|
+
fs.renameSync(temp, out);
|
|
180
|
+
log(`wrote ${out} (${timeline.duration.toFixed(1)}s)`);
|
|
181
|
+
return { out, duration: timeline.duration, width: project.config.width, height: project.config.height };
|
|
182
|
+
} finally {
|
|
183
|
+
if (browser) await browser.close();
|
|
184
|
+
if (server) await server.close();
|
|
185
|
+
fs.rmSync(temp, { recursive: true, force: true });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// ffmpeg and ffprobe helpers.
|
|
2
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
3
|
+
|
|
4
|
+
export function ffmpegPath() {
|
|
5
|
+
return process.env.EXPLAINROO_FFMPEG || 'ffmpeg';
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function ffprobePath() {
|
|
9
|
+
return process.env.EXPLAINROO_FFPROBE || 'ffprobe';
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function ffmpegVersion() {
|
|
13
|
+
const r = spawnSync(ffmpegPath(), ['-version'], { encoding: 'utf8' });
|
|
14
|
+
if (r.error || r.status !== 0) return null;
|
|
15
|
+
return r.stdout.split('\n')[0];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function run(bin, args, { input } = {}) {
|
|
19
|
+
return new Promise((resolve, reject) => {
|
|
20
|
+
const p = spawn(bin, args, { stdio: ['pipe', 'pipe', 'pipe'] });
|
|
21
|
+
let out = '';
|
|
22
|
+
let err = '';
|
|
23
|
+
p.stdout.on('data', (d) => (out += d));
|
|
24
|
+
p.stderr.on('data', (d) => (err += d));
|
|
25
|
+
p.on('error', (e) => reject(new Error(`${bin} could not start: ${e.message}. Install ffmpeg or set EXPLAINROO_FFMPEG.`)));
|
|
26
|
+
p.on('close', (code) => {
|
|
27
|
+
if (code === 0) resolve({ stdout: out, stderr: err });
|
|
28
|
+
else reject(new Error(`${bin} ${args.slice(0, 6).join(' ')} ... failed (${code}):\n${err.split('\n').slice(-12).join('\n')}`));
|
|
29
|
+
});
|
|
30
|
+
if (input) p.stdin.end(input);
|
|
31
|
+
else p.stdin.end();
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function ffmpeg(args, opts) {
|
|
36
|
+
return run(ffmpegPath(), ['-hide_banner', '-y', ...args], opts);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// A long-running encoder fed with JPEG or PNG frames on stdin.
|
|
40
|
+
export function frameEncoder({ fps, out, draft, format = 'mp4', transparent = false }) {
|
|
41
|
+
const codec = format === 'webm'
|
|
42
|
+
? ['-c:v', 'libvpx-vp9', '-crf', draft ? '32' : '24', '-b:v', '0', '-deadline', 'good', '-cpu-used', draft ? '4' : '2', '-auto-alt-ref', '0', '-pix_fmt', transparent ? 'yuva420p' : 'yuv420p', '-r', String(fps), '-g', String(fps * 2)]
|
|
43
|
+
: format === 'mov'
|
|
44
|
+
? ['-c:v', 'prores_ks', '-profile:v', '4', '-pix_fmt', transparent ? 'yuva444p10le' : 'yuv444p10le', '-r', String(fps)]
|
|
45
|
+
: ['-c:v', 'libx264', '-preset', draft ? 'veryfast' : 'medium', '-crf', draft ? '24' : '17', '-tune', 'animation', '-pix_fmt', 'yuv420p', '-r', String(fps), '-g', String(fps * 2)];
|
|
46
|
+
const args = [
|
|
47
|
+
'-hide_banner', '-y', '-loglevel', 'error',
|
|
48
|
+
'-f', 'image2pipe', '-framerate', String(fps), '-c:v', transparent ? 'png' : 'mjpeg', '-i', '-',
|
|
49
|
+
...codec,
|
|
50
|
+
out,
|
|
51
|
+
];
|
|
52
|
+
const p = spawn(ffmpegPath(), args, { stdio: ['pipe', 'ignore', 'pipe'] });
|
|
53
|
+
let err = '';
|
|
54
|
+
p.stderr.on('data', (d) => (err += d));
|
|
55
|
+
const done = new Promise((resolve, reject) => {
|
|
56
|
+
p.on('error', (e) => reject(new Error(`ffmpeg could not start: ${e.message}`)));
|
|
57
|
+
p.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`ffmpeg encoder failed (${code}): ${err.slice(-800)}`))));
|
|
58
|
+
});
|
|
59
|
+
done.catch(() => {});
|
|
60
|
+
return {
|
|
61
|
+
write(buf) {
|
|
62
|
+
if (p.stdin.write(buf)) return Promise.resolve();
|
|
63
|
+
return new Promise((r) => p.stdin.once('drain', r));
|
|
64
|
+
},
|
|
65
|
+
async close() {
|
|
66
|
+
p.stdin.end();
|
|
67
|
+
await done;
|
|
68
|
+
},
|
|
69
|
+
kill() {
|
|
70
|
+
try { p.kill('SIGKILL'); } catch {}
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Two-pass loudness normalization to `target` LUFS, peak-limited.
|
|
76
|
+
export async function normalizeLoudness(input, output, target = -14, sampleRate = 48000) {
|
|
77
|
+
const base = `I=${target}:TP=-1.5:LRA=11`;
|
|
78
|
+
const pass1 = await ffmpeg(['-i', input, '-af', `loudnorm=${base}:print_format=json`, '-f', 'null', '-']);
|
|
79
|
+
const json = pass1.stderr.slice(pass1.stderr.lastIndexOf('{'), pass1.stderr.lastIndexOf('}') + 1);
|
|
80
|
+
const m = JSON.parse(json);
|
|
81
|
+
// Silence and very short clips have no measurable integrated loudness.
|
|
82
|
+
if (!Number.isFinite(Number(m.input_i))) {
|
|
83
|
+
await ffmpeg(['-i', input, '-ar', String(sampleRate), '-c:a', 'pcm_s16le', output]);
|
|
84
|
+
return { inputI: Number(m.input_i), inputTP: Number(m.input_tp) };
|
|
85
|
+
}
|
|
86
|
+
const measured = `measured_I=${m.input_i}:measured_TP=${m.input_tp}:measured_LRA=${m.input_lra}:measured_thresh=${m.input_thresh}:offset=${m.target_offset}`;
|
|
87
|
+
await ffmpeg(['-i', input, '-af', `loudnorm=${base}:${measured}:linear=true:print_format=summary`, '-ar', String(sampleRate), '-c:a', 'pcm_s16le', output]);
|
|
88
|
+
return { inputI: Number(m.input_i), inputTP: Number(m.input_tp) };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function probe(file) {
|
|
92
|
+
const { stdout } = await run(ffprobePath(), ['-v', 'error', '-show_streams', '-show_format', '-of', 'json', file]);
|
|
93
|
+
return JSON.parse(stdout);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export async function loudness(file) {
|
|
97
|
+
const { stderr } = await ffmpeg(['-nostats', '-i', file, '-filter_complex', 'ebur128=peak=true', '-f', 'null', '-']);
|
|
98
|
+
const summary = stderr.slice(stderr.lastIndexOf('Summary:'));
|
|
99
|
+
const I = /I:\s*(-?[\d.]+) LUFS/.exec(summary);
|
|
100
|
+
const LRA = /LRA:\s*(-?[\d.]+) LU/.exec(summary);
|
|
101
|
+
const peak = /Peak:\s*(-?[\d.]+|-inf) dBFS/.exec(summary);
|
|
102
|
+
return { integrated: I ? Number(I[1]) : null, range: LRA ? Number(LRA[1]) : null, truePeak: peak ? Number(peak[1]) : null };
|
|
103
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { cacheRoot } from './models.js';
|
|
6
|
+
|
|
7
|
+
const SOURCE = 'https://raw.githubusercontent.com/googlefonts/noto-cjk/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans';
|
|
8
|
+
const FONTS = {
|
|
9
|
+
ja: { family: 'Noto Sans JP', dir: 'Japanese', name: 'NotoSansCJKjp', hashes: ['68a3fc98800b2a27b371f2fb79991daf3633bd89309d4ffaa6946fd587f375b5', 'e53dcb0dcb2922e45d01aae1ebd2f382bb81d4229b18b6b883bd170678af1f76'] },
|
|
10
|
+
zh: { family: 'Noto Sans SC', dir: 'SimplifiedChinese', name: 'NotoSansCJKsc', hashes: ['2c76254f6fc379fddfce0a7e84fb5385bb135d3e399294f6eeb6680d0365b74b', 'b5f0d1a190a7f9b43c310a8850630af12553df32c4c050543f9059732d9b4c0a'] },
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export function languageFonts(language) {
|
|
14
|
+
if (!Object.hasOwn(FONTS, language)) return [];
|
|
15
|
+
const f = FONTS[language];
|
|
16
|
+
return [400, 700].map((weight, i) => ({
|
|
17
|
+
family: f.family, weight, file: `${language}-${weight}.otf`,
|
|
18
|
+
path: path.join(cacheRoot(), 'fonts', `${language}-${weight}.otf`),
|
|
19
|
+
url: `${SOURCE}/OTF/${f.dir}/${f.name}-${i ? 'Bold' : 'Regular'}.otf`,
|
|
20
|
+
hash: f.hashes[i],
|
|
21
|
+
}));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function valid(data, hash) {
|
|
25
|
+
return data.subarray(0, 4).toString() === 'OTTO' && crypto.createHash('sha256').update(data).digest('hex') === hash;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function ensureFonts(language, { log = () => {} } = {}) {
|
|
29
|
+
const fonts = languageFonts(language);
|
|
30
|
+
if (!fonts.length) return;
|
|
31
|
+
for (const f of fonts) {
|
|
32
|
+
if (fs.existsSync(f.path) && valid(fs.readFileSync(f.path), f.hash)) continue;
|
|
33
|
+
if (process.env.EXPLAINROO_OFFLINE === '1') throw new Error(`${f.family} is missing or damaged. Run this command once without EXPLAINROO_OFFLINE to download the fonts.`);
|
|
34
|
+
log(`downloading ${f.family} ${f.weight === 700 ? 'Bold' : 'Regular'} (about 17 MB, first use only)`);
|
|
35
|
+
try {
|
|
36
|
+
const response = await fetch(f.url);
|
|
37
|
+
if (!response.ok) throw new Error();
|
|
38
|
+
const data = Buffer.from(await response.arrayBuffer());
|
|
39
|
+
if (!valid(data, f.hash)) throw new Error();
|
|
40
|
+
fs.mkdirSync(path.dirname(f.path), { recursive: true });
|
|
41
|
+
const temp = `${f.path}.${crypto.randomBytes(8).toString('hex')}.part`;
|
|
42
|
+
try {
|
|
43
|
+
fs.writeFileSync(temp, data);
|
|
44
|
+
fs.renameSync(temp, f.path);
|
|
45
|
+
} finally { fs.rmSync(temp, { force: true }); }
|
|
46
|
+
} catch {
|
|
47
|
+
throw new Error(`${f.family} could not be downloaded or checked. Check your connection and run the command again.`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const license = path.join(cacheRoot(), 'fonts', 'NotoSansCJK-OFL.txt');
|
|
51
|
+
if (!fs.existsSync(license)) {
|
|
52
|
+
if (process.env.EXPLAINROO_OFFLINE === '1') throw new Error('the Noto font license is missing. Run once without EXPLAINROO_OFFLINE to download it.');
|
|
53
|
+
const response = await fetch(`${SOURCE}/LICENSE`);
|
|
54
|
+
if (!response.ok) throw new Error('the Noto font license could not be downloaded. Check your connection and try again.');
|
|
55
|
+
const data = Buffer.from(await response.arrayBuffer());
|
|
56
|
+
if (crypto.createHash('sha256').update(data).digest('hex') !== '6a73f9541c2de74158c0e7cf6b0a58ef774f5a780bf191f2d7ec9cc53efe2bf2') throw new Error('the Noto font license could not be checked. Try again.');
|
|
57
|
+
fs.writeFileSync(license, data);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
let hb;
|
|
62
|
+
|
|
63
|
+
// Keeps only the characters in text, so an exported player loads a few
|
|
64
|
+
// kilobytes of font instead of the full 16 MB file.
|
|
65
|
+
export function subsetFont(data, text) {
|
|
66
|
+
hb ??= new WebAssembly.Instance(new WebAssembly.Module(fs.readFileSync(createRequire(import.meta.url).resolve('harfbuzzjs/dist/harfbuzz-subset.wasm')))).exports;
|
|
67
|
+
const pointer = hb.malloc(data.byteLength);
|
|
68
|
+
new Uint8Array(hb.memory.buffer).set(data, pointer);
|
|
69
|
+
const blob = hb.hb_blob_create(pointer, data.byteLength, 2, 0, 0);
|
|
70
|
+
const face = hb.hb_face_create(blob, 0);
|
|
71
|
+
hb.hb_blob_destroy(blob);
|
|
72
|
+
const input = hb.hb_subset_input_create_or_fail();
|
|
73
|
+
const unicodes = hb.hb_subset_input_unicode_set(input);
|
|
74
|
+
for (const c of new Set(text)) hb.hb_set_add(unicodes, c.codePointAt(0));
|
|
75
|
+
const result = hb.hb_subset_or_fail(face, input);
|
|
76
|
+
hb.hb_subset_input_destroy(input);
|
|
77
|
+
hb.hb_face_destroy(face);
|
|
78
|
+
hb.free(pointer);
|
|
79
|
+
if (!result) throw new Error('a font could not be reduced to the characters of the video.');
|
|
80
|
+
const out = hb.hb_face_reference_blob(result);
|
|
81
|
+
const start = hb.hb_blob_get_data(out, 0);
|
|
82
|
+
const bytes = Buffer.from(new Uint8Array(hb.memory.buffer).slice(start, start + hb.hb_blob_get_length(out)));
|
|
83
|
+
hb.hb_blob_destroy(out);
|
|
84
|
+
hb.hb_face_destroy(result);
|
|
85
|
+
return bytes;
|
|
86
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
import json
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
sys.stdin.reconfigure(encoding='utf-8')
|
|
6
|
+
sys.stdout.reconfigure(encoding='utf-8')
|
|
7
|
+
sys.stderr.reconfigure(encoding='utf-8')
|
|
8
|
+
|
|
9
|
+
mode = sys.argv[1]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
DIGITS = ['ゼロ', 'イチ', 'ニ', 'サン', 'ヨン', 'ゴ', 'ロク', 'ナナ', 'ハチ', 'キュー']
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def below_10000(n):
|
|
16
|
+
th, h, t, o = n // 1000, n // 100 % 10, n // 10 % 10, n % 10
|
|
17
|
+
out = {1: 'セン', 3: 'サンゼン', 8: 'ハッセン'}.get(th, DIGITS[th] + 'セン') if th else ''
|
|
18
|
+
out += {1: 'ヒャク', 3: 'サンビャク', 6: 'ロッピャク', 8: 'ハッピャク'}.get(h, DIGITS[h] + 'ヒャク') if h else ''
|
|
19
|
+
out += ('' if t == 1 else DIGITS[t]) + 'ジュー' if t else ''
|
|
20
|
+
return out + (DIGITS[o] if o else '')
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def number(digits):
|
|
24
|
+
# UniDic leaves digits unread. Whisper may write a number in digits or
|
|
25
|
+
# kana, so both sides get the same reading.
|
|
26
|
+
n = int(digits)
|
|
27
|
+
if n == 0 or n >= 10 ** 8 or digits[0] == '0':
|
|
28
|
+
return ''.join(DIGITS[int(d)] for d in digits)
|
|
29
|
+
man, rest = divmod(n, 10000)
|
|
30
|
+
return (below_10000(man) + 'マン' if man else '') + below_10000(rest)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def readings(tagger, text):
|
|
34
|
+
# [start, end, katakana reading] for each word, in characters.
|
|
35
|
+
out, pos, decimal = [], 0, False
|
|
36
|
+
for word in tagger(text):
|
|
37
|
+
start = text.find(word.surface, pos)
|
|
38
|
+
if start < 0:
|
|
39
|
+
continue
|
|
40
|
+
pos = start + len(word.surface)
|
|
41
|
+
pron = getattr(word.feature, 'pron', None)
|
|
42
|
+
surface = word.surface
|
|
43
|
+
if surface.isascii() and surface.isdigit():
|
|
44
|
+
# After a decimal point, digits are read one by one.
|
|
45
|
+
reading = ''.join(DIGITS[int(d)] for d in surface) if decimal else number(surface)
|
|
46
|
+
elif surface == '.' and out and text[start - 1:start].isdigit() and text[pos:pos + 1].isdigit():
|
|
47
|
+
reading = 'テン'
|
|
48
|
+
else:
|
|
49
|
+
reading = pron if pron and pron != '*' else surface
|
|
50
|
+
decimal = reading == 'テン' or (decimal and surface.isdigit())
|
|
51
|
+
out.append([start, pos, reading])
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
with contextlib.redirect_stdout(sys.stderr):
|
|
57
|
+
# Mandarin 1.1 uses a different phoneme alphabet from Kokoro v1.0.
|
|
58
|
+
if mode == 'ja':
|
|
59
|
+
from misaki.ja import JAG2P
|
|
60
|
+
g2p = JAG2P()
|
|
61
|
+
run = lambda text: g2p(text)[0]
|
|
62
|
+
elif mode == 'zh':
|
|
63
|
+
from misaki.zh import ZHG2P
|
|
64
|
+
g2p = ZHG2P(version=None)
|
|
65
|
+
run = lambda text: g2p(text)[0]
|
|
66
|
+
else:
|
|
67
|
+
# The speech check compares Japanese by sound, with the UniDic
|
|
68
|
+
# dictionary misaki uses.
|
|
69
|
+
import fugashi
|
|
70
|
+
tagger = fugashi.Tagger()
|
|
71
|
+
run = lambda text: readings(tagger, text)
|
|
72
|
+
for line in sys.stdin:
|
|
73
|
+
print(json.dumps(run(json.loads(line)), ensure_ascii=False), file=sys.__stdout__, flush=True)
|
|
74
|
+
except Exception as error:
|
|
75
|
+
print(f'{type(error).__name__}: {error}'.splitlines()[0], file=sys.stderr)
|
|
76
|
+
sys.exit(1)
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// Optional illustrations through OpenRouter. Needs OPENROUTER_API_KEY in the
|
|
2
|
+
// environment or in a .env file in the project folder or the explainroo
|
|
3
|
+
// folder. Every request is logged with its cost in build/images/usage.jsonl.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import { findEnv } from './env.js';
|
|
8
|
+
import { ProjectError } from './project.js';
|
|
9
|
+
|
|
10
|
+
export const IMAGE_MODELS = {
|
|
11
|
+
best: 'openai/gpt-5.4-image-2',
|
|
12
|
+
cheap: 'google/gemini-3.1-flash-image',
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const ASPECTS = ['16:9', '9:16', '1:1', '4:3', '3:4', '3:2', '2:3'];
|
|
16
|
+
|
|
17
|
+
export const DEFAULT_STYLE =
|
|
18
|
+
'Flat illustration for a friendly how-to video, soft colors, simple shapes, clear subject in the middle, plain light background, no text, no letters, no numbers, no logos, no watermark.';
|
|
19
|
+
|
|
20
|
+
export function findKey(projectDir) {
|
|
21
|
+
return findEnv('OPENROUTER_API_KEY', projectDir);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function resolveModel(name) {
|
|
25
|
+
if (!name) return IMAGE_MODELS.best;
|
|
26
|
+
if (IMAGE_MODELS[name]) return IMAGE_MODELS[name];
|
|
27
|
+
if (/^[\w.-]+\/[\w.:-]+$/.test(name)) return name;
|
|
28
|
+
throw new ProjectError(`image model must be "best", "cheap" or an OpenRouter model id like ${IMAGE_MODELS.best}`);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function toDataUrl(file) {
|
|
32
|
+
const ext = path.extname(file).toLowerCase().slice(1);
|
|
33
|
+
const mime = ext === 'jpg' || ext === 'jpeg' ? 'image/jpeg' : ext === 'webp' ? 'image/webp' : 'image/png';
|
|
34
|
+
return `data:${mime};base64,${fs.readFileSync(file).toString('base64')}`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Generates one image and saves it as assets/<name>.<ext>.
|
|
38
|
+
export async function generateImage(project, { name, prompt, model, aspect, refs = [], style, log = () => {} }) {
|
|
39
|
+
if (!name || !/^[\w-]+$/.test(name)) throw new ProjectError('the image name may only use letters, digits, "-" and "_" (it becomes assets/<name>.png)');
|
|
40
|
+
if (!prompt || prompt.trim().length < 8) throw new ProjectError('describe the image in a sentence or two');
|
|
41
|
+
const key = findKey(project.dir);
|
|
42
|
+
if (!key) {
|
|
43
|
+
throw new ProjectError('images need an OpenRouter API key. Ask the user for one (openrouter.ai/keys), then set OPENROUTER_API_KEY or put OPENROUTER_API_KEY=... in a .env file in the explainroo folder.');
|
|
44
|
+
}
|
|
45
|
+
const cfg = project.config.images || {};
|
|
46
|
+
const modelId = resolveModel(model || cfg.model);
|
|
47
|
+
const ratio = aspect || (project.config.height > project.config.width ? '9:16' : project.config.height === project.config.width ? '1:1' : '16:9');
|
|
48
|
+
if (!ASPECTS.includes(ratio)) throw new ProjectError(`aspect must be one of ${ASPECTS.join(', ')}`);
|
|
49
|
+
const styleText = style === false ? '' : (style || cfg.style || DEFAULT_STYLE);
|
|
50
|
+
const text = `${prompt.trim()}\n\nStyle: ${styleText}\nAspect ratio: ${ratio}.`.trim();
|
|
51
|
+
const content = [{ type: 'text', text }];
|
|
52
|
+
for (const r of refs) {
|
|
53
|
+
// Accept paths relative to the project (assets/a.png) or to the current folder.
|
|
54
|
+
const file = [path.resolve(project.dir, r), path.resolve(r)].find((f) => fs.existsSync(f));
|
|
55
|
+
if (!file) throw new ProjectError(`reference image ${r} does not exist (use a path like assets/${path.basename(r)})`);
|
|
56
|
+
content.push({ type: 'image_url', image_url: { url: toDataUrl(file) } });
|
|
57
|
+
}
|
|
58
|
+
const body = {
|
|
59
|
+
model: modelId,
|
|
60
|
+
messages: [{ role: 'user', content }],
|
|
61
|
+
modalities: ['image', 'text'],
|
|
62
|
+
image_config: { aspect_ratio: ratio },
|
|
63
|
+
usage: { include: true },
|
|
64
|
+
};
|
|
65
|
+
const t0 = Date.now();
|
|
66
|
+
let res;
|
|
67
|
+
let json;
|
|
68
|
+
for (let attempt = 1; attempt <= 2; attempt++) {
|
|
69
|
+
const ctrl = new AbortController();
|
|
70
|
+
const timer = setTimeout(() => ctrl.abort(), 300000);
|
|
71
|
+
try {
|
|
72
|
+
res = await fetch('https://openrouter.ai/api/v1/chat/completions', {
|
|
73
|
+
method: 'POST',
|
|
74
|
+
signal: ctrl.signal,
|
|
75
|
+
headers: {
|
|
76
|
+
Authorization: `Bearer ${key}`,
|
|
77
|
+
'Content-Type': 'application/json',
|
|
78
|
+
'HTTP-Referer': 'https://explainroo.com',
|
|
79
|
+
'X-Title': 'explainroo',
|
|
80
|
+
},
|
|
81
|
+
body: JSON.stringify(body),
|
|
82
|
+
});
|
|
83
|
+
json = await res.json().catch(() => null);
|
|
84
|
+
} catch (e) {
|
|
85
|
+
if (attempt === 2) throw new Error(`OpenRouter request failed: ${e.name === 'AbortError' ? 'no answer after 5 minutes' : e.message}`);
|
|
86
|
+
log('OpenRouter did not answer, trying once more');
|
|
87
|
+
continue;
|
|
88
|
+
} finally {
|
|
89
|
+
clearTimeout(timer);
|
|
90
|
+
}
|
|
91
|
+
if (res.status >= 500 && attempt === 1) {
|
|
92
|
+
log(`OpenRouter returned ${res.status}, trying once more`);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
if (!res.ok) {
|
|
98
|
+
const msg = json?.error?.message || `HTTP ${res.status}`;
|
|
99
|
+
if (res.status === 401) throw new ProjectError(`OpenRouter rejected the API key (${msg}). Ask the user to check it.`);
|
|
100
|
+
if (res.status === 402) throw new ProjectError(`the OpenRouter account has no credit left (${msg}).`);
|
|
101
|
+
throw new Error(`OpenRouter error: ${msg}`);
|
|
102
|
+
}
|
|
103
|
+
const msg = json?.choices?.[0]?.message;
|
|
104
|
+
const url = msg?.images?.[0]?.image_url?.url;
|
|
105
|
+
if (!url || !url.startsWith('data:')) {
|
|
106
|
+
const said = typeof msg?.content === 'string' ? msg.content.slice(0, 300) : '';
|
|
107
|
+
throw new Error(`the model returned no image${said ? `. It said: "${said}"` : ''}. Try another wording or the other model.`);
|
|
108
|
+
}
|
|
109
|
+
const [, mime, b64] = /^data:([^;]+);base64,(.*)$/s.exec(url) || [];
|
|
110
|
+
const ext = mime === 'image/jpeg' ? 'jpg' : mime === 'image/webp' ? 'webp' : 'png';
|
|
111
|
+
const assets = path.join(project.dir, 'assets');
|
|
112
|
+
fs.mkdirSync(assets, { recursive: true });
|
|
113
|
+
for (const e of ['png', 'jpg', 'webp']) fs.rmSync(path.join(assets, `${name}.${e}`), { force: true });
|
|
114
|
+
const file = path.join(assets, `${name}.${ext}`);
|
|
115
|
+
const buf = Buffer.from(b64, 'base64');
|
|
116
|
+
fs.writeFileSync(file, buf);
|
|
117
|
+
|
|
118
|
+
const usage = json.usage || {};
|
|
119
|
+
const entry = {
|
|
120
|
+
time: new Date().toISOString(),
|
|
121
|
+
name,
|
|
122
|
+
file: path.relative(project.dir, file),
|
|
123
|
+
provider: 'openrouter',
|
|
124
|
+
model: modelId,
|
|
125
|
+
served_by: json.model || modelId,
|
|
126
|
+
aspect: ratio,
|
|
127
|
+
prompt: prompt.trim(),
|
|
128
|
+
style: styleText,
|
|
129
|
+
refs,
|
|
130
|
+
cost_usd: typeof usage.cost === 'number' ? usage.cost : null,
|
|
131
|
+
prompt_tokens: usage.prompt_tokens ?? null,
|
|
132
|
+
completion_tokens: usage.completion_tokens ?? null,
|
|
133
|
+
seconds: Math.round((Date.now() - t0) / 100) / 10,
|
|
134
|
+
bytes: buf.length,
|
|
135
|
+
sha256: crypto.createHash('sha256').update(buf).digest('hex').slice(0, 16),
|
|
136
|
+
};
|
|
137
|
+
const logDir = path.join(project.paths.build, 'images');
|
|
138
|
+
fs.mkdirSync(logDir, { recursive: true });
|
|
139
|
+
fs.appendFileSync(path.join(logDir, 'usage.jsonl'), JSON.stringify(entry) + '\n');
|
|
140
|
+
return { ...entry, file, total_usd: imageSpend(project) };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function imageLog(project) {
|
|
144
|
+
const p = path.join(project.paths.build, 'images', 'usage.jsonl');
|
|
145
|
+
if (!fs.existsSync(p)) return [];
|
|
146
|
+
return fs.readFileSync(p, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l));
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function imageSpend(project) {
|
|
150
|
+
return Math.round(imageLog(project).reduce((a, e) => a + (e.cost_usd || 0), 0) * 10000) / 10000;
|
|
151
|
+
}
|