Skip to content

The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.

Studio: add Doubao recorded-speech recognition (#47)

wang135531e70d9d93c7be
diff --git a/.changeset/doubao-speech-recognition.md b/.changeset/doubao-speech-recognition.md
new file mode 100644
index 0000000..3964513
--- /dev/null
+++ b/.changeset/doubao-speech-recognition.md
@@ -0,0 +1,7 @@
+---
+"openfilm": patch
+---
+
+Speech recognition with Doubao using your Volcengine Speech API key, with word-timed transcripts from audio and video recordings.
+
+Keep transcript lines visible through their timed words, even when speech is slower than the estimated reading time.
diff --git a/packages/openfilm/studio/server/captions.test.mjs b/packages/openfilm/studio/server/captions.test.mjs
index 3463a8c..70475b2 100644
--- a/packages/openfilm/studio/server/captions.test.mjs
+++ b/packages/openfilm/studio/server/captions.test.mjs
@@ -46,6 +46,28 @@ test('a transcript breaks into lines at sentence ends, timed by its words', () =
assert.deepEqual(spokenLines('', WORDS, 3000), []);
});
+test('a slowly spoken line lasts through its words instead of the text-length estimate', () => {
+ const words = [
+ { token: 'One', startSec: 0, endSec: 0.5 },
+ { token: 'two.', startSec: 4, endSec: 5 },
+ { token: 'Three.', startSec: 6, endSec: 6.5 },
+ ];
+ const lines = spokenLines('One two. Three.', words, 7000);
+ assert.ok(lines[0].endMs >= 5000, 'the last word finishes before the line ends');
+ assert.ok(lines[0].endMs < 6000, 'a long silence still clears the line');
+ assert.equal(lines[1].endMs, 7000, 'the final line stays within the source');
+ for (const line of lines) assert.ok(line.marks.every((m) => m.startMs < line.endMs));
+
+ const close = spokenLines('One two. Three.', [words[0], words[1], { ...words[2], startSec: 5.2 }], 7000);
+ assert.equal(close[0].endMs, 5200, 'the next line still bounds the previous one');
+});
+
+test('word starts alone also keep a slow line visible through its final mark', () => {
+ const [line] = spokenLines('One two.', [{ token: 'One', startSec: 0 }, { token: 'two.', startSec: 4 }]);
+ assert.ok(line.endMs > 4000);
+ assert.ok(line.marks.every((m) => m.startMs < line.endMs));
+});
+
test('subtitles leave out fillers and false starts', () => {
assert.equal(captionText('uh, so we th- the plan'), 'so we the plan');
assert.equal(captionText('um...'), '');
diff --git a/packages/openfilm/studio/server/get.mjs b/packages/openfilm/studio/server/get.mjs
index 8ab7cfb..3a2328d 100644
--- a/packages/openfilm/studio/server/get.mjs
+++ b/packages/openfilm/studio/server/get.mjs
@@ -310,7 +310,7 @@ export async function runGet(root, verb, given, { via, model, yes = false, ask,
root,
signal: clock.signal,
say: (/** @type {string} */ line) => { said.push(line); },
- read: (/** @type {string} */ path) => readInput(root, path, verb === 'asr' && path === args.src, clock.signal),
+ read: (/** @type {string} */ path) => readInput(root, path, verb === 'asr' && path === args.src, clock.signal, provider.speechFormat),
};
try {
if (verb === 'video' && !yes) {
@@ -367,10 +367,10 @@ function deadline(seconds, outer) {
};
}
-/** A project file for a provider: as it is, or (`speech`) the sound alone, small. @param {string} root @param {string} rel @param {boolean} speech @param {AbortSignal} signal */
-async function readInput(root, rel, speech, signal) {
+/** A project file for a provider: as it is, or (`speech`) the sound alone, small. @param {string} root @param {string} rel @param {boolean} speech @param {AbortSignal} signal @param {'mp3'} [speechFormat] */
+async function readInput(root, rel, speech, signal, speechFormat) {
const abs = inside(root, rel);
- const bytes = speech ? await speechOf(abs, signal) : await readFile(abs);
+ const bytes = speech ? await speechOf(abs, signal, speechFormat) : await readFile(abs);
if (bytes.length > MAX_INPUT_BYTES) {
throw new GetError(speech
? `${rel} is too long to transcribe in one go (${Math.round(bytes.length / 1e6)} MB of speech even compressed, about ${Math.round(bytes.length / 3000 / 3600)} hours). Split it into parts first.`
@@ -382,9 +382,19 @@ async function readInput(root, rel, speech, signal) {
/**
* The speech of a recording, as transcription needs it: mono, 16 kHz, low bitrate, in the same format as the file (its
* name and extension go with it). An hour of video is gigabytes; its speech this way is about 11 MB.
- * @param {string} abs @param {AbortSignal} signal
+ * @param {string} abs @param {AbortSignal} signal @param {'mp3'} [speechFormat]
*/
-async function speechOf(abs, signal) {
+async function speechOf(abs, signal, speechFormat) {
+ // A provider may require MP3 regardless of the source container. Stream it without temporary files.
+ if (speechFormat === 'mp3') {
+ return new Promise((done, fail) => {
+ execFile('ffmpeg', ['-nostdin', '-v', 'error', '-i', abs, '-vn', '-map', '0:a:0', '-ac', '1', '-ar', '16000', '-af', 'aresample=async=1:first_pts=0', '-c:a', 'libmp3lame', '-b:a', '32k', '-f', 'mp3', 'pipe:1'],
+ { signal, windowsHide: true, encoding: 'buffer', maxBuffer: MAX_INPUT_BYTES }, (error, out) => {
+ if (error) return fail(new GetError('Could not prepare MP3 speech for transcription. Check the audio track, FFmpeg and recording length. No audio was uploaded.'));
+ done(out);
+ });
+ });
+ }
const ext = extname(abs).toLowerCase();
const format = ['.mp4', '.m4a', '.m4v', '.mov', '.3gp'].includes(ext) ? { codec: ['-c:a', 'aac', '-b:a', '32k'], f: 'mp4' }
: ext === '.mp3' ? { codec: ['-c:a', 'libmp3lame', '-b:a', '32k'], f: 'mp3' }
diff --git a/packages/openfilm/studio/server/get.test.mjs b/packages/openfilm/studio/server/get.test.mjs
index 76828ef..e018d67 100644
--- a/packages/openfilm/studio/server/get.test.mjs
+++ b/packages/openfilm/studio/server/get.test.mjs
@@ -379,11 +379,11 @@ test('openfilm get: what can be got here, connected, partly or not at all; wrong
/* nothing connected: no verbs, what to do instead */
rmSync(providersFile());
const nothing = get(scratch);
- assert.equal(nothing.status, 0);
+ assert.equal(nothing.status, 0, nothing.stderr);
assert.equal(nothing.stdout, 'Nothing is connected for media here: each kind works only once the person connects a service that makes it (below). '
+ 'Until then, make sound and pictures in code, or use a service the person has a key for (with its API docs), and save them under assets/. '
+ `\`openfilm get <what> --help\` shows what one kind takes (${media.join(', ')}).\n\n${services()}\n`);
- assert.match(services(), /^Media services, each used with the person's own key: Azure Speech \(voice-over\), Brave Search \(web search\), ElevenLabs \(voice-over, sound effects, music, transcripts\), fal\.ai \(images, video, music, sound effects\), .*, Tavily \(web search\)\. In Studio, the OpenFilm logo at the top left opens Settings/);
+ assert.match(services(), /^Media services, each used with the person's own key: Azure Speech \(voice-over\), Brave Search \(web search\), Doubao \(transcripts\), ElevenLabs \(voice-over, sound effects, music, transcripts\), fal\.ai \(images, video, music, sound effects\), .*, Tavily \(web search\)\. In Studio, the OpenFilm logo at the top left opens Settings/);
/* partly: what is connected, then one line for the rest with the services that make each, then the services there
are; never who makes what is connected */
diff --git a/packages/openfilm/studio/server/providers/contract.mjs b/packages/openfilm/studio/server/providers/contract.mjs
index 73ea2b5..e059315 100644
--- a/packages/openfilm/studio/server/providers/contract.mjs
+++ b/packages/openfilm/studio/server/providers/contract.mjs
@@ -55,7 +55,7 @@
*/
/**
- * `read`: a project file's bytes (for `asr`, the speech alone: a small mono copy in the same format).
+ * `read`: a project file's bytes (for `asr`, the speech alone: a small mono copy, in `speechFormat` when requested).
* `model`: the id of the model, one of the provider's `models` for the verb, the person chose (a provider uses its first
* when there is none).
* @typedef {{
@@ -78,6 +78,7 @@
* verbs: Verb[],
* models?: Partial<Record<Verb, { id: string, name: string }[]>>,
* checkKey?: (key: string) => void,
+ * speechFormat?: 'mp3',
* run: (verb: Verb, args: Record<string, unknown>, ctx: RunContext) => Promise<RunResult>,
* }} Provider
* `models`: the models it can make each kind of media with, its default first, each with the name people know it by
diff --git a/packages/openfilm/studio/server/providers/doubao.mjs b/packages/openfilm/studio/server/providers/doubao.mjs
new file mode 100644
index 0000000..bde160a
--- /dev/null
+++ b/packages/openfilm/studio/server/providers/doubao.mjs
@@ -0,0 +1,65 @@
+// @ts-check
+/** Doubao recorded-speech recognition with the person's Volcengine Speech API key. */
+import { randomUUID } from 'node:crypto';
+import { billedBy, needed, noBalance, serviceUrl } from './common.mjs';
+
+const NAME = 'Doubao';
+const MODEL = 'volc.bigasr.auc_turbo';
+const ENDPOINT = 'https://openspeech.bytedance.com/api/v3/auc/bigmodel/recognize/flash';
+/** Convert only actual service timestamps, in milliseconds, to OpenFilm words in seconds.
+ * @param {any} body @param {string | null} status */
+export function doubaoResult(body, status) {
+ if (status !== '20000000') throw new Error('Doubao did not report recognition success. Check Speech service access and balance. Not retried.');
+ const result = body?.result;
+ if (!result || typeof result.text !== 'string' || !Array.isArray(result.utterances)) throw new Error('Doubao returned no transcript or utterance timestamps.');
+ const words = [];
+ const duration = body?.audio_info?.duration;
+ let previous = -1;
+ for (const line of result.utterances) {
+ if (!Array.isArray(line?.words)) throw new Error('Doubao returned no word timestamps.');
+ for (const w of line.words) {
+ if (!w || typeof w.text !== 'string' || !w.text.trim()) continue;
+ if (typeof w.start_time !== 'number' || typeof w.end_time !== 'number') throw new Error('Doubao returned nonnumeric timestamps.');
+ const start = w.start_time / 1000, end = w.end_time / 1000;
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || end < start || start < previous
+ || (typeof duration === 'number' && Number.isFinite(duration) && duration > 0 && w.end_time > duration + 150)) throw new Error('Doubao returned invalid or out-of-range word timestamps.');
+ words.push({ token: w.text, start, end });
+ previous = start;
+ }
+ }
+ // ITN can turn spoken words into numbers or symbols in result.text. Keep both service outputs as returned.
+ if (!words.length) throw new Error('Doubao returned no word timestamps.');
+ return { text: result.text, words };
+}
+
+/** @type {import('./contract.mjs').Provider} */
+export default {
+ id: 'doubao', name: NAME, env: 'DOUBAO_ASR_API_KEY', speechFormat: 'mp3',
+ keysUrl: 'https://console.volcengine.com/speech/app',
+ billingUrl: 'https://console.volcengine.com/finance/overview/',
+ verbs: ['asr'], models: { asr: [{ id: MODEL, name: MODEL }] },
+ async run(verb, args, ctx) {
+ if (verb !== 'asr') throw new Error(`${NAME} does not do ${verb}.`);
+ const src = needed(args, 'src');
+ const bytes = Buffer.from(await ctx.read(src));
+ if (!bytes.length || bytes.length >= 100_000_000) throw new Error('Doubao requires audio smaller than 100 MB. No audio was uploaded.');
+ const requestId = randomUUID();
+ let response;
+ try {
+ response = await fetch(serviceUrl('DOUBAO', ENDPOINT), {
+ method: 'POST', redirect: 'error', signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(180_000)]),
+ headers: { 'Content-Type': 'application/json', 'X-Api-Key': ctx.key, 'X-Api-Resource-Id': MODEL, 'X-Api-Request-Id': requestId, 'X-Api-Sequence': '-1' },
+ body: JSON.stringify({ user: { uid: 'openfilm-local' }, audio: { data: bytes.toString('base64') }, request: { model_name: 'bigmodel', enable_itn: true, enable_punc: true, enable_ddc: false, show_utterances: true } }),
+ });
+ } catch { throw new Error(`Doubao was interrupted or timed out and may have charged. Check the console before retrying. Request id: ${requestId}. Not retried.`); }
+ const status = response.headers.get('X-Api-Status-Code');
+ if (!response.ok) {
+ if (response.status === 402) throw noBalance(NAME);
+ throw new Error(`Doubao HTTP ${response.status}. Use a Volcengine Speech API key with flash recognition access (not an Ark chat key), and check the balance. Request id: ${requestId}. Not retried.`);
+ }
+ const body = await response.json();
+ const result = doubaoResult(body, status);
+ return { files: [], index: [{ src, ...result, transcribed: true }],
+ receipt: { provider: 'doubao', model: MODEL, src, text: result.text, words: result.words.length, requestId }, cost: billedBy(NAME) };
+ },
+};
diff --git a/packages/openfilm/studio/server/providers/doubao.test.mjs b/packages/openfilm/studio/server/providers/doubao.test.mjs
new file mode 100644
index 0000000..7eaa75b
--- /dev/null
+++ b/packages/openfilm/studio/server/providers/doubao.test.mjs
@@ -0,0 +1,183 @@
+import { test, before, after } from 'node:test';
+import assert from 'node:assert/strict';
+import { createServer } from 'node:http';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, mkdirSync, readFileSync, readdirSync, existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import doubao, { doubaoResult } from './doubao.mjs';
+import { providerKey, changeSettings } from '../keys.mjs';
+import { chooseProvider } from './index.mjs';
+import { runGet } from '../get.mjs';
+import { readTranscript } from '../transcripts.mjs';
+
+const fixture = () => ({ audio_info: { duration: 2000 }, result: { text: '你好,AI native。', utterances: [{ words: [
+ { text: '你', start_time: 100, end_time: 300 }, { text: '好', start_time: 300, end_time: 600 },
+ { text: ' ', start_time: -1, end_time: -1 }, { text: 'AI', start_time: 800, end_time: 1000 },
+ { text: 'native', start_time: 1100, end_time: 1800 },
+] }] } });
+let server;
+let reply = (_req, res) => res.writeHead(200, { 'Content-Type': 'application/json', 'X-Api-Status-Code': '20000000' }).end(JSON.stringify(fixture()));
+const seen = [];
+const oldUrl = process.env.OPENFILM_DOUBAO_URL;
+before(async () => {
+ server = createServer(async (req, res) => {
+ const chunks = [];
+ for await (const chunk of req) chunks.push(chunk);
+ seen.push({ url: req.url, headers: req.headers, body: JSON.parse(Buffer.concat(chunks)) });
+ reply(req, res);
+ });
+ await new Promise(done => server.listen(0, '127.0.0.1', done));
+ process.env.OPENFILM_DOUBAO_URL = `http://127.0.0.1:${server.address().port}/recognize/flash`;
+});
+after(async () => {
+ await new Promise(done => server.close(done));
+ if (oldUrl === undefined) delete process.env.OPENFILM_DOUBAO_URL;
+ else process.env.OPENFILM_DOUBAO_URL = oldUrl;
+});
+
+test('word timings are real and numeric; whitespace-only tokens are ignored', () => {
+ const result = doubaoResult(fixture(), '20000000');
+ assert.deepEqual(result.words[2], { token: 'AI', start: 0.8, end: 1 });
+ assert.equal(result.words.length, 4);
+ assert.throws(() => doubaoResult(fixture(), '45000001'));
+ for (const change of [
+ b => b.result.utterances[0].words = [],
+ b => b.result.utterances[0].words[0].end_time = 9000,
+ b => b.result.utterances[0].words[1].start_time = 0,
+ b => b.result.utterances[0].words[0].start_time = null,
+ b => b.result.utterances[0].words = {},
+ ]) {
+ const body = fixture(); change(body);
+ assert.throws(() => doubaoResult(body, '20000000'));
+ }
+});
+
+test('normalized numbers and symbols may differ from spoken word tokens', () => {
+ const body = { result: { text: 'AI 增长了 20%。', utterances: [{ words: [
+ { text: 'AI', start_time: 0, end_time: 300 },
+ { text: '增长了', start_time: 300, end_time: 800 },
+ { text: '百分之二十', start_time: 800, end_time: 1600 },
+ ] }] } };
+ const result = doubaoResult(body, '20000000');
+ assert.equal(result.text, body.result.text);
+ assert.deepEqual(result.words[2], { token: '百分之二十', start: 0.8, end: 1.6 });
+});
+
+test('replays word timings from a real Doubao response for non-sensitive synthetic speech', () => {
+ // Recorded 2026-10-15, volc.bigasr.auc_turbo, 4.623-second synthesized English audio.
+ // No credentials, request identifiers, source paths or user recordings are included.
+ const tokens = [['Hello', 210, 530], ['This', 1370, 1610], ['is', 1610, 1810],
+ ['an', 1810, 2090], ['audio', 2130, 2450], ['transcription', 2610, 3290], ['test', 3450, 3730]];
+ const words = tokens.flatMap(([text, start_time, end_time], i) => [
+ ...(i ? [{ text: ' ', start_time: -1, end_time: -1 }] : []), { text, start_time, end_time },
+ ]);
+ const result = doubaoResult({ audio_info: { duration: 4623 }, result: {
+ text: 'Hello. This is an audio transcription test.', utterances: [{ words }],
+ } }, '20000000');
+ assert.equal(result.text, 'Hello. This is an audio transcription test.');
+ assert.deepEqual(result.words, tokens.map(([token, start, end]) => ({ token, start: start / 1000, end: end / 1000 })));
+});
+
+test('native key settings honor explicit keys, environment keys and disconnect', () => {
+ const settings = { keys: {}, use: {}, model: {}, off: [], custom: [] };
+ const env = { DOUBAO_ASR_API_KEY: 'fake-env-key' };
+ assert.equal(providerKey(doubao, settings, env).source, 'env');
+ assert.equal(providerKey(doubao, { ...settings, off: ['doubao'] }, env), null);
+ assert.equal(providerKey(doubao, { ...settings, keys: { doubao: 'fake-explicit-key' } }, env).key, 'fake-explicit-key');
+});
+
+test('MP4 to fake Doubao to word-timed VTT; cache reuse, HTTP failures and uncertain requests', async () => {
+ // Retain this isolated synthetic project for inspection; never use an installed Studio or real credentials.
+ const root = mkdtempSync(join(tmpdir(), 'openfilm-doubao-test-'));
+ mkdirSync(join(root, 'assets'));
+ const oldHome = process.env.OPENFILM_HOME;
+ process.env.OPENFILM_HOME = join(root, 'settings');
+ try {
+ execFileSync('ffmpeg', ['-nostdin', '-v', 'error', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=2', '-c:a', 'aac', join(root, 'assets', 'speech.mp4')], { windowsHide: true });
+ await changeSettings(s => { s.keys.doubao = 'fake-test-key'; s.use.asr = 'doubao'; });
+ assert.equal((await chooseProvider('asr')).id, 'doubao');
+ await runGet(root, 'asr', { src: 'assets/speech.mp4' });
+ assert.equal(seen.length, 1);
+ const sent = seen[0];
+ assert.equal(sent.url, '/recognize/flash');
+ assert.equal(sent.headers['x-api-key'], 'fake-test-key');
+ assert.equal(sent.headers['x-api-resource-id'], 'volc.bigasr.auc_turbo');
+ assert.equal(sent.headers['x-api-sequence'], '-1');
+ assert.ok(sent.headers['x-api-request-id']);
+ assert.equal(sent.body.request.show_utterances, true);
+ assert.equal(sent.body.request.enable_ddc, false);
+ const audio = Buffer.from(sent.body.audio.data, 'base64');
+ assert.ok(audio.toString('ascii', 0, 3) === 'ID3' || audio[0] === 255);
+ const transcript = await readTranscript(root, 'assets/speech.mp4');
+ assert.ok(transcript.lines.some(l => l.text.includes('AI native')));
+ const vtt = readFileSync(join(root, 'assets', 'speech.vtt'), 'utf8');
+ assert.ok(vtt.includes('<00:00:00.800>AI'));
+ assert.equal(existsSync(join(root, 'assets', 'asr')), false, 'provider does not write response files');
+ await runGet(root, 'asr', { src: 'assets/speech.mp4' });
+ assert.equal(seen.length, 1);
+ const force = () => runGet(root, 'asr', { src: 'assets/speech.mp4', force: true });
+ for (const status of [401, 403, 429, 500]) {
+ reply = (_req, res) => res.writeHead(status).end('fake-test-key');
+ const count = seen.length;
+ await assert.rejects(force(), e => e.message.includes(`HTTP ${status}`) && !e.message.includes('fake-test-key'));
+ assert.equal(seen.length, count + 1);
+ }
+ reply = (_req, res) => res.writeHead(402).end();
+ await assert.rejects(force(), /balance/);
+ reply = (_req, res) => res.writeHead(302, { location: process.env.OPENFILM_DOUBAO_URL }).end();
+ const beforeRedirect = seen.length;
+ await assert.rejects(force(), /Request id: [0-9a-f-]+\. Not retried/);
+ assert.equal(seen.length, beforeRedirect + 1, 'redirects do not resend credentials');
+ reply = (_req, res) => res.writeHead(200, { 'X-Api-Status-Code': '45000001' }).end(JSON.stringify(fixture()));
+ await assert.rejects(force(), /did not report recognition success/);
+ reply = (req) => req.socket.destroy();
+ const count = seen.length;
+ await assert.rejects(force(), /Not retried/);
+ assert.equal(seen.length, count + 1);
+ assert.equal(readFileSync(join(root, 'assets', 'speech.vtt'), 'utf8'), vtt);
+ assert.equal(existsSync(join(root, 'assets', 'asr')), false);
+ } finally {
+ if (oldHome === undefined) delete process.env.OPENFILM_HOME;
+ else process.env.OPENFILM_HOME = oldHome;
+ }
+});
+
+test('a real mixed-language response lands a VTT whose cues contain all timed words', async () => {
+ // Sanitized response from the 2026-10-15 live run on synthetic Chinese/English speech with numbers.
+ const text = '今天测试 AI native 价格是20元,增长20%,一共有三个视频。';
+ const tokens = [
+ ['今', 180, 420], ['天', 420, 660], ['测', 660, 900], ['试', 900, 1060],
+ ['AI', 1260, 1460], ['native', 1660, 1780], ['价', 2460, 2700], ['格', 2700, 2900],
+ ['是', 2900, 3220], ['20', 3220, 3580], ['元', 3580, 3860], ['增', 4220, 4540],
+ ['长', 4540, 4780], ['20%', 4820, 5860], ['一', 6220, 6460], ['共', 6460, 6660],
+ ['有', 6660, 6900], ['三', 6900, 7100], ['个', 7100, 7340], ['视', 7340, 7580], ['频', 7580, 7860],
+ ];
+ const body = { audio_info: { duration: 8676 }, result: { text, utterances: [{
+ text, start_time: 180, end_time: 7860,
+ words: tokens.map(([text, start_time, end_time]) => ({ text, start_time, end_time })),
+ }] } };
+ const root = mkdtempSync(join(tmpdir(), 'openfilm-doubao-mixed-'));
+ mkdirSync(join(root, 'assets'));
+ const oldHome = process.env.OPENFILM_HOME, oldReply = reply;
+ process.env.OPENFILM_HOME = join(root, 'settings');
+ try {
+ execFileSync('ffmpeg', ['-nostdin', '-v', 'error', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=9', '-c:a', 'aac', join(root, 'assets', 'speech.mp4')], { windowsHide: true });
+ await changeSettings(s => { s.keys.doubao = 'fake-test-key'; s.use.asr = 'doubao'; });
+ reply = (_req, res) => res.writeHead(200, { 'Content-Type': 'application/json', 'X-Api-Status-Code': '20000000' }).end(JSON.stringify(body));
+ await runGet(root, 'asr', { src: 'assets/speech.mp4' });
+ const { lines } = await readTranscript(root, 'assets/speech.mp4');
+ assert.equal(lines[0].endMs, 6220, 'the first cue lasts until the next cue, past its last word at 5860 ms');
+ assert.equal(lines.flatMap(l => l.marks ?? []).length, tokens.length);
+ for (const [, start, end] of tokens) {
+ const line = lines.find(l => l.marks?.some(m => m.startMs === start));
+ assert.ok(line && line.startMs <= start && line.endMs >= end, `word at ${start}–${end} is contained in its cue`);
+ }
+ for (const line of lines) assert.ok(line.marks.every(m => m.startMs < line.endMs));
+ assert.deepEqual(readdirSync(join(root, 'assets')).sort(), ['speech.mp4', 'speech.vtt']);
+ } finally {
+ reply = oldReply;
+ if (oldHome === undefined) delete process.env.OPENFILM_HOME;
+ else process.env.OPENFILM_HOME = oldHome;
+ }
+});
diff --git a/packages/openfilm/studio/server/providers/index.mjs b/packages/openfilm/studio/server/providers/index.mjs
index 7c1a287..908f011 100644
--- a/packages/openfilm/studio/server/providers/index.mjs
+++ b/packages/openfilm/studio/server/providers/index.mjs
@@ -25,6 +25,7 @@ import brave from './brave.mjs';
import tavily from './tavily.mjs';
import groq from './groq.mjs';
import azure from './azure.mjs';
+import doubao from './doubao.mjs';
/**
* @typedef {import('./contract.mjs').Provider} Provider @typedef {import('./contract.mjs').Verb} Verb
@@ -33,7 +34,7 @@ import azure from './azure.mjs';
*/
/** The providers paid with the person's own key. */
-const OWN = [elevenlabs, openai, google, fal, pexels, pixabay, brave, tavily, groq, azure];
+const OWN = [elevenlabs, openai, google, fal, pexels, pixabay, brave, tavily, groq, azure, doubao];
/** The kinds of media the person chooses a provider and model for (Settings → Models). */
const USE_VERBS = /** @type {Verb[]} */ (['tts', 'music', 'sfx', 'asr', 'image', 'image-search', 'video', 'translate', 'web-search']);
diff --git a/packages/openfilm/studio/server/providers/index.test.mjs b/packages/openfilm/studio/server/providers/index.test.mjs
index db3922e..a4d511f 100644
--- a/packages/openfilm/studio/server/providers/index.test.mjs
+++ b/packages/openfilm/studio/server/providers/index.test.mjs
@@ -8,14 +8,14 @@ import { chooseProvider, listProviders, shownChoices } from './index.mjs';
before(() => {
/* this machine's own keys must not decide these */
process.env.OPENFILM_HOME = mkdtempSync(join(tmpdir(), 'of-routing-'));
- for (const name of ['ELEVENLABS_API_KEY', 'OPENAI_API_KEY', 'GEMINI_API_KEY', 'GOOGLE_API_KEY', 'FAL_KEY', 'PEXELS_API_KEY', 'PIXABAY_API_KEY', 'BRAVE_API_KEY', 'TAVILY_API_KEY', 'GROQ_API_KEY', 'AZURE_SPEECH_KEY']) delete process.env[name];
+ for (const name of ['ELEVENLABS_API_KEY', 'OPENAI_API_KEY', 'GEMINI_API_KEY', 'GOOGLE_API_KEY', 'FAL_KEY', 'PEXELS_API_KEY', 'PIXABAY_API_KEY', 'BRAVE_API_KEY', 'TAVILY_API_KEY', 'GROQ_API_KEY', 'AZURE_SPEECH_KEY', 'DOUBAO_ASR_API_KEY']) delete process.env[name];
});
const settings = (keys = {}, use = {}) => ({ keys, use, model: {} });
const id = async (promise) => (await promise)?.id ?? null;
test('the own-key providers, in the order Settings lists them', () => {
- assert.deepEqual(listProviders().map((p) => p.id), ['elevenlabs', 'openai', 'google', 'fal', 'pexels', 'pixabay', 'brave', 'tavily', 'groq', 'azure']);
+ assert.deepEqual(listProviders().map((p) => p.id), ['elevenlabs', 'openai', 'google', 'fal', 'pexels', 'pixabay', 'brave', 'tavily', 'groq', 'azure', 'doubao']);
});
test('nothing serves a kind of media nobody chose, even with a key that could', async () => {
diff --git a/packages/openfilm/studio/server/transcripts.mjs b/packages/openfilm/studio/server/transcripts.mjs
index e21f6c4..91e6093 100644
--- a/packages/openfilm/studio/server/transcripts.mjs
+++ b/packages/openfilm/studio/server/transcripts.mjs
@@ -468,6 +468,7 @@ export function spokenLines(source, words, durMs) {
text: raw.trim(),
/* a piece with no matched word (all digits or marks) follows the one before */
startMs: inPiece[0] ? Math.round(inPiece[0].startSec * 1000) : 0,
+ spokenUntilMs: inPiece.reduce((end, m) => Math.max(end, Math.round((m.endSec ?? m.startSec) * 1000)), 0),
marks: inPiece.map((m) => ({ index: m.index - piece.from - lead, startMs: Math.round(m.startSec * 1000) })),
};
});
@@ -476,13 +477,13 @@ export function spokenLines(source, words, durMs) {
}
return started.map((one, i) => {
/* a line stays up until the next one starts (a gap would blank the line being read), the last until the source
- ends, unless that is a long silence: then about as long as it takes to say, plus GAP_MS */
+ ends, unless that is a long silence: then through its words or the estimated speaking time, plus GAP_MS */
const until = started[i + 1]?.startMs ?? total ?? Infinity;
const spoken = Math.max(500, cells(one.text) * FALLBACK_MS_PER_CELL);
return {
text: one.text,
startMs: one.startMs,
- endMs: Math.min(until, one.startMs + spoken + GAP_MS),
+ endMs: Math.min(until, Math.max(one.startMs + spoken, one.spokenUntilMs) + GAP_MS),
...(one.marks.length ? { marks: one.marks } : {}),
};
}).filter((l) => l.endMs > l.startMs);
diff --git a/packages/openfilm/studio/ui/src/lib/provider-marks.ts b/packages/openfilm/studio/ui/src/lib/provider-marks.ts
index 1fada55..8b1855a 100644
--- a/packages/openfilm/studio/ui/src/lib/provider-marks.ts
+++ b/packages/openfilm/studio/ui/src/lib/provider-marks.ts
@@ -6,6 +6,7 @@
*/
export const MARKS: Record<string, { viewBox: string; d: string; parts?: { d: string; opacity?: number }[] }> = {
+ doubao: { viewBox: '0 0 24 24', d: 'M5.31 15.756c.172-3.75 1.883-5.999 2.549-6.739-3.26 2.058-5.425 5.658-6.358 8.308v1.12C1.501 21.513 4.226 24 7.59 24a6.59 6.59 0 002.2-.375c.353-.12.7-.248 1.039-.378.913-.899 1.65-1.91 2.243-2.992-4.877 2.431-7.974.072-7.763-4.5l.002.001z M22.57 10.283c-1.212-.901-4.109-2.404-7.397-2.8.295 3.792.093 8.766-2.1 12.773a12.782 12.782 0 01-2.244 2.992c3.764-1.448 6.746-3.457 8.596-5.219 2.82-2.683 3.353-5.178 3.361-6.66a2.737 2.737 0 00-.216-1.084v-.002zM14.303 1.867C12.955.7 11.248 0 9.39 0 7.532 0 5.883.677 4.545 1.807 2.791 3.29 1.627 5.557 1.5 8.125v9.201c.932-2.65 3.097-6.25 6.357-8.307.5-.318 1.025-.595 1.569-.829 1.883-.801 3.878-.932 5.746-.706-.222-2.83-.718-5.002-.87-5.617h.001z M17.305 4.961a199.47 199.47 0 01-1.08-1.094c-.202-.213-.398-.419-.586-.622l-1.333-1.378c.151.615.648 2.786.869 5.617 3.288.395 6.185 1.898 7.396 2.8-1.306-1.275-3.475-3.487-5.266-5.323z' },
elevenlabs: { viewBox: '0 0 24 24', d: 'M5 0h5v24H5V0zM14 0h5v24h-5V0z' },
openai: { viewBox: '0 0 24 24', d: 'M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z' },
claude: { viewBox: '0 0 24 24', d: 'm4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z' },