78 lines
3.7 KiB
JavaScript
78 lines
3.7 KiB
JavaScript
#!/usr/bin/env node
|
|
// Generates Chinese narration for one episode (or all) with edge-tts.
|
|
// Audio/SRT are cached per scene; durations feed assemble.mjs.
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import { spawnSync } from "node:child_process";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
const args = process.argv.slice(2);
|
|
const option = (name, fallback = "") => {
|
|
const index = args.indexOf(name);
|
|
return index < 0 ? fallback : args[index + 1] ?? fallback;
|
|
};
|
|
const tts = "/home/mes123456/FreeCADWasmDev/working/FreeCAD/.venv-video/bin/edge-tts";
|
|
const ffprobe = "ffprobe";
|
|
const voices = ["zh-CN-XiaoxiaoNeural", "zh-CN-YunjianNeural", "zh-CN-YunxiNeural"];
|
|
|
|
function episodeIds() {
|
|
const requested = option("--episode");
|
|
if (requested) return [requested];
|
|
const course = JSON.parse(fs.readFileSync(path.join(here, "course.json"), "utf8"));
|
|
return course.episodes.map(episode => episode.id);
|
|
}
|
|
|
|
function synthesize(episode) {
|
|
const episodeDir = path.join(here, "episodes", episode);
|
|
const scriptPath = path.join(episodeDir, "script.zh.json");
|
|
if (!fs.existsSync(scriptPath)) throw new Error(`missing script ${scriptPath}`);
|
|
const script = JSON.parse(fs.readFileSync(scriptPath, "utf8"));
|
|
const audioDir = path.join(episodeDir, "audio");
|
|
fs.mkdirSync(audioDir, { recursive: true });
|
|
const durations = {};
|
|
const voiceList = [script.voice, ...voices].filter(Boolean);
|
|
for (const scene of script.scenes) {
|
|
const media = path.join(audioDir, `${scene.id}.mp3`);
|
|
const subtitles = path.join(audioDir, `${scene.id}.srt`);
|
|
let ok = fs.existsSync(media) && fs.statSync(media).size > 1000 && fs.existsSync(subtitles);
|
|
let lastError = "";
|
|
for (const voice of voiceList) {
|
|
for (let attempt = 0; attempt < 2 && !ok; attempt++) {
|
|
const result = spawnSync(tts, ["--voice", voice, `--rate=${script.rate ?? "-4%"}`,
|
|
"--text", scene.narration, "--write-media", media, "--write-subtitles", subtitles],
|
|
{ encoding: "utf8", timeout: 120000 });
|
|
if (result.status === 0 && fs.existsSync(media) && fs.statSync(media).size > 1000) {
|
|
ok = true;
|
|
console.log(JSON.stringify({ episode, scene: scene.id, voice, bytes: fs.statSync(media).size }));
|
|
} else {
|
|
lastError = `${result.status}: ${(result.stderr || result.stdout || "").slice(-300)}`;
|
|
console.log(JSON.stringify({ episode, scene: scene.id, voice, attempt, error: lastError }));
|
|
}
|
|
}
|
|
if (ok) break;
|
|
}
|
|
if (!ok) throw new Error(`TTS failed for ${episode}/${scene.id}: ${lastError}`);
|
|
const probe = spawnSync(ffprobe, ["-v", "error", "-show_entries", "format=duration",
|
|
"-of", "default=nw=1:nk=1", media], { encoding: "utf8" });
|
|
const duration = Number(probe.stdout.trim());
|
|
if (!Number.isFinite(duration) || duration <= 0) throw new Error(`Invalid duration for ${episode}/${scene.id}`);
|
|
durations[scene.id] = {
|
|
title: scene.title, target: scene.target, duration: Math.round(duration * 1000) / 1000,
|
|
media: path.relative(episodeDir, media), subtitles: path.relative(episodeDir, subtitles),
|
|
};
|
|
}
|
|
fs.writeFileSync(path.join(episodeDir, "audio-durations.json"), `${JSON.stringify({
|
|
schema: "freecad-web-line-course/video-tts/v1",
|
|
episode, generatedAt: new Date().toISOString(),
|
|
voice: script.voice, rate: script.rate, scenes: durations,
|
|
}, null, 2)}\n`);
|
|
return durations;
|
|
}
|
|
|
|
const results = {};
|
|
for (const episode of episodeIds()) {
|
|
results[episode] = synthesize(episode);
|
|
}
|
|
console.log(JSON.stringify({ ok: true, episodes: Object.keys(results), scenes: Object.values(results).reduce((sum, item) => sum + Object.keys(item).length, 0) }));
|