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.

Add Gemini audio transcription (#132)

Kefa Mgayab8bda5ea66dd
diff --git a/.changeset/google-gemini-transcription.md b/.changeset/google-gemini-transcription.md
new file mode 100644
index 0000000..f4b95c1
--- /dev/null
+++ b/.changeset/google-gemini-transcription.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Transcribe audio for captions with Gemini 3.5 Transcribe and a Google Gemini API key, including word-level timing.
diff --git a/packages/openfilm/studio/server/providers/google.mjs b/packages/openfilm/studio/server/providers/google.mjs
index d5806fd..133f62a 100644
--- a/packages/openfilm/studio/server/providers/google.mjs
+++ b/packages/openfilm/studio/server/providers/google.mjs
@@ -1,11 +1,12 @@
// @ts-check
/**
- * Google's Gemini API with the person's own key: pictures, video (Veo), voice-over and subtitle translation. REST API
- * (https://ai.google.dev/api), key in `x-goog-api-key`. Pictures, speech and text come from `generateContent`; a video
- * is a long-running operation, asked after until it is done. Its speech has no word timings and comes as raw PCM,
- * wrapped here in a WAV file.
+ * Google's Gemini API with the person's own key: pictures, video (Veo), voice-over, transcription and subtitle
+ * translation. REST API (https://ai.google.dev/api), key in `x-goog-api-key`. Pictures, speech and text come from
+ * `generateContent`; transcription uses Gemini Transcribe through the Interactions API; a video is a long-running
+ * operation, asked after until it is done. Generated speech has no word timings and comes as raw PCM, wrapped here in
+ * a WAV file.
*/
-import { RATIO_SIZE, billedBy, call, clamp, download, extOf, imageSize, landing, list, madePicture, mimeOf, modelOf, needed, notes, number, ownAddress, serviceUrl, sleep, text, translatedLines, translationAsk, wav, wavSeconds } from './common.mjs';
+import { RATIO_SIZE, billedBy, call, clamp, download, extOf, imageSize, landing, list, madePicture, mimeOf, modelOf, needed, notes, number, ownAddress, serviceUrl, sleep, speechUpload, text, translatedLines, translationAsk, wav, wavSeconds } from './common.mjs';
/** @typedef {import('./contract.mjs').Provider} Provider @typedef {import('./contract.mjs').RunContext} RunContext */
@@ -13,6 +14,7 @@ const NAME = 'Google';
/** the models it makes each kind of media with, the default first (https://ai.google.dev/gemini-api/docs/models) */
const MODELS = {
tts: [{ id: 'gemini-3.8-flash-tts', name: 'Gemini 3.8 Flash TTS' }, { id: 'gemini-3.8-flash-lite-tts', name: 'Gemini 3.8 Flash-Lite TTS' }],
+ asr: [{ id: 'gemini-3.5-transcribe', name: 'Gemini 3.5 Transcribe' }],
image: [
{ id: 'gemini-3.1-flash-image', name: 'Gemini 3.1 Flash Image' },
{ id: 'gemini-3-pro-image', name: 'Nano Banana Pro' },
@@ -52,7 +54,7 @@ export default {
keysUrl: 'https://aistudio.google.com/apikey',
/* AI Studio's keys page is where a key's project shows its billing */
billingUrl: 'https://aistudio.google.com/apikey',
- verbs: ['voice', 'tts', 'image', 'video', 'translate'],
+ verbs: ['voice', 'tts', 'image', 'video', 'asr', 'translate'],
models: MODELS,
async run(verb, args, ctx) {
const base = serviceUrl('GOOGLE', 'https://generativelanguage.googleapis.com');
@@ -94,6 +96,34 @@ export default {
cost: billedBy(NAME),
};
}
+ if (verb === 'asr') {
+ const src = needed(args, 'src');
+ const upload = await speechUpload(src, ctx);
+ const model = modelOf(MODELS, 'asr', ctx);
+ const file = await uploadFile(upload, base, send);
+ try {
+ const body = await (await send(`${base}/v1beta/interactions`, {
+ method: 'POST',
+ body: JSON.stringify({
+ model,
+ input: [{ type: 'audio', uri: file.uri, mime_type: file.mimeType }],
+ generation_config: { transcription_config: { mode: { type: 'verbatim', timestamp_granularities: ['word'] } } },
+ }),
+ })).json();
+ const words = interactionWords(body);
+ const said = interactionText(body);
+ if (said && !words.length) throw new Error(`${NAME} answered without word timestamps.`);
+ return {
+ files: [],
+ index: [{ src, text: said, words, transcribed: true }],
+ receipt: { provider: 'google', model, src, text: said, words: words.length },
+ cost: billedBy(NAME),
+ };
+ } finally {
+ /* Files otherwise remain in the person's Gemini project for up to 48 hours. Cleanup must not hide the ASR result. */
+ if (/^files\/[a-z0-9-]+$/i.test(file.name)) await send(`${base}/v1beta/${file.name}`, { method: 'DELETE' }).catch(() => {});
+ }
+ }
if (verb === 'image') {
const prompt = needed(args, 'prompt');
const ratio = text(args.ratio) || '3:2';
@@ -128,6 +158,72 @@ export default {
},
};
+/**
+ * A prepared speech file uploaded with Gemini's resumable Files API. The returned upload address is accepted only on
+ * Google's configured origin, so the person's key and bytes cannot be redirected elsewhere.
+ * @param {{ blob: Blob, name: string, size: number }} upload @param {string} base
+ * @param {(url: string, init?: RequestInit) => Promise<Response>} send
+ */
+async function uploadFile(upload, base, send) {
+ const mimeType = upload.blob.type || mimeOf(upload.name);
+ const started = await send(`${base}/upload/v1beta/files`, {
+ method: 'POST',
+ headers: {
+ 'x-goog-upload-protocol': 'resumable',
+ 'x-goog-upload-command': 'start',
+ 'x-goog-upload-header-content-length': String(upload.size),
+ 'x-goog-upload-header-content-type': mimeType,
+ },
+ body: JSON.stringify({ file: { display_name: upload.name } }),
+ });
+ const uploadUrl = ownAddress(NAME, started.headers.get('x-goog-upload-url'), base);
+ const body = await (await send(uploadUrl, {
+ method: 'POST',
+ headers: {
+ 'content-type': mimeType,
+ 'content-length': String(upload.size),
+ 'x-goog-upload-offset': '0',
+ 'x-goog-upload-command': 'upload, finalize',
+ },
+ body: upload.blob,
+ })).json();
+ const file = body?.file;
+ const uri = text(file?.uri), name = text(file?.name);
+ if (!uri || !name) throw new Error(`${NAME} did not keep the speech upload.`);
+ return { uri, name, mimeType: text(file?.mimeType ?? file?.mime_type) || mimeType };
+}
+
+/** Seconds from a protobuf duration such as `0.450s`. @param {unknown} value */
+function offsetSeconds(value) {
+ const raw = typeof value === 'string' ? value.trim().replace(/s$/, '') : value;
+ const seconds = Number(raw);
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
+}
+
+/** The text output parts of a completed interaction. @param {any} body */
+function interactionContents(body) {
+ return (Array.isArray(body?.steps) ? body.steps : [])
+ .filter((/** @type {any} */ step) => !step?.type || step.type === 'model_output')
+ .flatMap((/** @type {any} */ step) => Array.isArray(step?.content) ? step.content : []);
+}
+
+/** @param {any} body */
+function interactionText(body) {
+ const direct = text(body?.output_text ?? body?.outputText);
+ return direct || interactionContents(body).map((/** @type {any} */ part) => text(part?.text)).filter(Boolean).join(' ').trim();
+}
+
+/** Gemini word annotations as OpenFilm's provider word contract. @param {any} body */
+function interactionWords(body) {
+ return interactionContents(body).flatMap((/** @type {any} */ part) => Array.isArray(part?.annotations) ? part.annotations : [])
+ .filter((/** @type {any} */ a) => a?.type === 'word_info' && text(a?.text))
+ .map((/** @type {any} */ a) => {
+ const start = offsetSeconds(a.start_offset ?? a.startOffset);
+ const end = offsetSeconds(a.end_offset ?? a.endOffset);
+ return start === null ? null : { token: text(a.text), start, end: end === null || end < start ? start : end };
+ }).filter(Boolean);
+}
+
/** The first inline file of a `generateContent` answer, or a sentence saying why there is none. */
function inline(/** @type {any} */ body, /** @type {string} */ what) {
const parts = body?.candidates?.[0]?.content?.parts ?? [];
diff --git a/packages/openfilm/studio/server/providers/google.test.mjs b/packages/openfilm/studio/server/providers/google.test.mjs
index 3a07b8f..cf2c00f 100644
--- a/packages/openfilm/studio/server/providers/google.test.mjs
+++ b/packages/openfilm/studio/server/providers/google.test.mjs
@@ -15,9 +15,9 @@ before(async () => {
for await (const c of req) chunks.push(c);
const call = { method: req.method, url: new URL(req.url, 'http://x'), headers: req.headers, body: Buffer.concat(chunks) };
seen.push(call);
- const [status, body] = await reply(call);
- if (Buffer.isBuffer(body)) res.writeHead(status, { 'content-type': 'video/mp4' }).end(body);
- else res.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(body));
+ const [status, body, headers = {}] = await reply(call);
+ if (Buffer.isBuffer(body)) res.writeHead(status, { 'content-type': 'video/mp4', ...headers }).end(body);
+ else res.writeHead(status, { 'content-type': 'application/json', ...headers }).end(JSON.stringify(body));
});
await new Promise((done) => server.listen(0, '127.0.0.1', done));
base = `http://127.0.0.1:${server.address().port}`;
@@ -41,6 +41,39 @@ test('voice-over: the raw PCM wrapped as a WAV, its length from the samples', as
assert.equal(result.index[0].dur, 1);
});
+test('transcription: speech is uploaded, word timestamps returned, and the temporary file deleted', async () => {
+ reply = (call) => {
+ if (call.url.pathname === '/upload/v1beta/files') {
+ return [200, {}, { 'x-goog-upload-url': `${base}/upload/session-1` }];
+ }
+ if (call.url.pathname === '/upload/session-1') {
+ assert.equal(call.headers['x-goog-upload-command'], 'upload, finalize');
+ assert.equal(call.headers['content-type'], 'audio/mpeg');
+ return [200, { file: { name: 'files/audio-1', uri: `${base}/v1beta/files/audio-1`, mimeType: 'audio/mpeg' } }];
+ }
+ if (call.url.pathname === '/v1beta/interactions') {
+ return [200, { status: 'completed', steps: [{ type: 'model_output', content: [{
+ type: 'text', text: 'Hello world.', annotations: [
+ { type: 'word_info', text: 'Hello', start_offset: '0.100s', end_offset: '0.450s' },
+ { type: 'word_info', text: 'world.', start_offset: '0.500s', end_offset: '0.850s' },
+ ],
+ }] }] }];
+ }
+ if (call.method === 'DELETE' && call.url.pathname === '/v1beta/files/audio-1') return [200, {}];
+ return [404, {}];
+ };
+ const mp3 = new Uint8Array(Buffer.from('ID3 speech bytes'));
+ const result = await google.run('asr', { src: 'assets/interview.mp3' }, ctx({ 'assets/interview.mp3': mp3 }));
+ const interaction = seen.findLast((call) => call.url.pathname === '/v1beta/interactions');
+ const sent = JSON.parse(interaction.body);
+ assert.equal(sent.model, 'gemini-3.5-transcribe');
+ assert.deepEqual(sent.generation_config.transcription_config.mode, { type: 'verbatim', timestamp_granularities: ['word'] });
+ assert.deepEqual(result.index, [{ src: 'assets/interview.mp3', text: 'Hello world.', words: [
+ { token: 'Hello', start: 0.1, end: 0.45 }, { token: 'world.', start: 0.5, end: 0.85 },
+ ], transcribed: true }]);
+ assert.ok(seen.some((call) => call.method === 'DELETE' && call.url.pathname === '/v1beta/files/audio-1'));
+});
+
test('a picture: the ratio and size asked, the extension from what came back, transparency noted', async () => {
const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xc0, 0, 17, 8, 0x02, 0xd0, 0x05, 0x00, 3, 0, 0, 0, 0]);
reply = () => [200, inline('image/jpeg', jpeg)];
diff --git a/packages/openfilm/studio/server/providers/index.test.mjs b/packages/openfilm/studio/server/providers/index.test.mjs
index a4d511f..dab935a 100644
--- a/packages/openfilm/studio/server/providers/index.test.mjs
+++ b/packages/openfilm/studio/server/providers/index.test.mjs
@@ -28,6 +28,7 @@ test('the person\'s choice serves while it can; a key gone serves nothing', asyn
const keys = { elevenlabs: 'xi-0123456789', google: 'AIza-0123456789' };
assert.equal(await id(chooseProvider('tts', { settings: settings(keys, { tts: 'google' }) })), 'google');
assert.equal(await id(chooseProvider('voice', { settings: settings(keys, { tts: 'google' }) })), 'google');
+ assert.equal(await id(chooseProvider('asr', { settings: settings(keys, { asr: 'google' }) })), 'google');
assert.equal(await id(chooseProvider('tts', { settings: settings({}, { tts: 'google' }) })), null);
});