全部 kit / 程式 kit
bilingual-subtitle-kit
雙語字幕:VTT 解析 + 漸進背景翻譯(並行+重試)+ Web Storage 快取,translate 後端可注入
版本 v0.2.0 · 更新 2026-11-13
範例
repo 裡的 example.js,整份照登。 在 GitHub 上看
// 示範:解析一小段 VTT,用假的 translate(把英文轉大寫)翻譯,印出雙語結果。
// 執行:node example.js
'use strict';
const kit = require('./index');
// 一段最小 VTT
const vtt = `WEBVTT
00:00:00.000 --> 00:00:02.000
Hello world
00:00:02.000 --> 00:00:05.000
This is a bilingual subtitle demo
00:00:05.000 --> 00:00:08.000
The translate function is injectable
`;
// 假 translate:符合合約 translate(texts, {from,to}) => Promise<string[]>
// 這裡單純把每句轉大寫當作「翻譯」,實務上請換成 DeepL / Google / OpenAI / 自架 API。
async function fakeTranslate(texts, { from, to }) {
await new Promise((r) => setTimeout(r, 10)); // 模擬網路延遲
return texts.map((t) => `[${to}] ` + t.toUpperCase());
}
async function main() {
// 1. 解析 VTT
const subs = kit.parseVTT(vtt);
console.log(`解析出 ${subs.length} 句字幕\n`);
// 2. 建立漸進翻譯佇列(注入 fakeTranslate)
const queue = kit.createQueue({
translate: fakeTranslate,
to: 'zh-TW',
batchSize: 2,
concurrency: 2,
onProgress: (done, total) => console.log(` 進度:${done}/${total}`),
});
// 3. 先翻前 2 句(漸進),再背景翻完剩下的
await queue.initialize(subs, 2);
await queue.translateRemaining();
// 4. 印出雙語結果
console.log('\n雙語字幕:');
for (const s of queue.getAllSubtitles()) {
console.log(` [${s.start.toFixed(1)}s-${s.end.toFixed(1)}s]`);
console.log(` 原文:${s.text}`);
console.log(` 譯文:${s.translation}`);
}
// 5. 時間點查詢
const at = queue.getSubtitleAt(3);
console.log(`\n第 3 秒正在顯示:${at ? at.text : '(無)'}`);
// 6. 快取在 Node 無 storage → 自動降級
const cache = kit.createCache();
console.log(`\n快取可用(此環境):${cache.available}`);
console.log(`\n進度:${JSON.stringify(queue.getProgress())}`);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});