The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.
Studio: Azure Speech as a voice-over provider (#8)
Bo Lu6a1d9b8363b9
diff --git a/.changeset/azure-speech-provider.md b/.changeset/azure-speech-provider.mdnew file mode 100644index 0000000..67216c1--- /dev/null+++ b/.changeset/azure-speech-provider.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: Azure Speech (Azure AI Speech) can be connected under Settings → Providers for voice-over with its neural voices. The key carries the resource's region (`<region>:<key>`, or `AZURE_SPEECH_KEY` with `AZURE_SPEECH_REGION`), and one without a region is refused where it is pasted; Azure times no words, so subtitles spread the text over the line, as with OpenAI's voices.diff --git a/packages/openfilm/studio/server/get.test.mjs b/packages/openfilm/studio/server/get.test.mjsindex 47ff051..a3d9564 100644--- a/packages/openfilm/studio/server/get.test.mjs+++ b/packages/openfilm/studio/server/get.test.mjs@@ -383,7 +383,7 @@ test('openfilm get: what can be got here, connected, partly or not at all; wrongassert.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: 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\), 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 thereare; never who makes what is connected */diff --git a/packages/openfilm/studio/server/keys.test.mjs b/packages/openfilm/studio/server/keys.test.mjsindex a65cac5..417ed36 100644--- a/packages/openfilm/studio/server/keys.test.mjs+++ b/packages/openfilm/studio/server/keys.test.mjs@@ -14,7 +14,7 @@ before(async () => {const scratch = mkdtempSync(join(tmpdir(), 'of-keys-'));process.env.OPENFILM_HOME = join(scratch, 'home');process.env.OPENFILM_LIBRARY = join(scratch, 'library');- 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']) 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', 'AZURE_SPEECH_REGION']) delete process.env[name];studio = await startStudio({ port: 0, openBrowser: (url) => opened.push(url) });});after(() => studio.close());@@ -107,6 +107,23 @@ test('a provider\'s own page for its balance opens in the person\'s browser, forassert.equal((await api('/api/providers/acme/billing', { method: 'POST' })).status, 404);});+test('a provider that checks its pasted key refuses one that cannot work, where it is pasted', async () => {+ delete process.env.AZURE_SPEECH_REGION;+ const bare = await api('/api/providers/azure/key', { method: 'PUT', body: { key: 'azure-test-0123456789abcdef' } });+ assert.equal(bare.status, 400);+ assert.match((await bare.json()).error, /region/);+ const placed = await api('/api/providers/azure/key', { method: 'PUT', body: { key: 'eastus:azure-test-0123456789abcdef' } });+ assert.equal(placed.status, 200);+ assert.equal((await placed.json()).providers.find((p) => p.id === 'azure').last4, 'cdef');+ process.env.AZURE_SPEECH_REGION = 'westus2';+ try {+ assert.equal((await api('/api/providers/azure/key', { method: 'PUT', body: { key: 'azure-test-0123456789abcdef' } })).status, 200);+ } finally {+ delete process.env.AZURE_SPEECH_REGION;+ }+ await api('/api/providers/azure/key', { method: 'DELETE' });+});+test('a key removed: what it made goes to another key that makes it, else to nothing', async () => {await api('/api/providers/openai/key', { method: 'PUT', body: { key: 'sk-test-OPENAI00001' } });await api('/api/providers/google/key', { method: 'PUT', body: { key: 'AIza-test-GOOGLE0001' } });diff --git a/packages/openfilm/studio/server/providers/azure.mjs b/packages/openfilm/studio/server/providers/azure.mjsnew file mode 100644index 0000000..b9865c9--- /dev/null+++ b/packages/openfilm/studio/server/providers/azure.mjs@@ -0,0 +1,100 @@+// @ts-check+/**+ * Azure Speech with the person's own key: voice-over from the neural voices of Azure AI Speech+ * (https://learn.microsoft.com/azure/ai-services/speech-service/rest-text-to-speech), as WAV, with no word timings: a+ * voice-over's words are left to Studio to spread over the line.+ *+ * Azure's address carries the resource's region (`https://<region>.tts.speech.microsoft.com`), so the key must say it:+ * pasted as `<region>:<key>` (e.g. `eastus:a1b2…`), or `AZURE_SPEECH_KEY` with the region in `AZURE_SPEECH_REGION`.+ * There is no model to choose: each voice (`en-US-AvaMultilingualNeural`, …) is its own, picked with `--voice`.+ */+import { billedBy, call, clamp, landing, needed, notes, number, serviceUrl, text, wavSeconds } from './common.mjs';++/** @typedef {import('./contract.mjs').Provider} Provider */++const NAME = 'Azure Speech';+/** WAV straight from the service: its length is read from the file itself. */+const FORMAT = 'riff-24khz-16bit-mono-pcm';++/**+ * The region and the key proper from what the person gave: `<region>:<key>`, else the key with `AZURE_SPEECH_REGION`.+ * A sentence when the region is nowhere, or does not look like one (it becomes the host name): a guess would send the+ * key to the wrong address and fail as "bad key". `checkKey` runs this when the key is pasted, so a key that cannot+ * work is refused where it is pasted, not at the first voice-over.+ */+function placed(/** @type {string} */ raw) {+ const split = /^([a-z0-9]+):(.{8,})$/i.exec(raw);+ if (split) return { region: split[1].toLowerCase(), key: split[2] };+ const region = text(process.env.AZURE_SPEECH_REGION).toLowerCase();+ if (!region) throw new Error(`${NAME} needs the resource's region: paste the key as <region>:<key> (e.g. eastus:a1b2…) in Studio, or set AZURE_SPEECH_REGION.`);+ if (!/^[a-z0-9]+$/.test(region)) throw new Error(`AZURE_SPEECH_REGION does not look like an Azure region (letters and digits, e.g. eastus): ${region}`);+ return { region, key: raw };+}++/** Text inside SSML: the five XML escapes. */+const xml = (/** @type {string} */ s) => s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c] ?? c);++/** @type {Provider} */+export default {+ id: 'azure',+ name: NAME,+ env: 'AZURE_SPEECH_KEY',+ keysUrl: 'https://portal.azure.com/#view/Microsoft_Azure_ProjectOxford/CognitiveServicesHub/~/SpeechServices',+ billingUrl: 'https://portal.azure.com/#view/Microsoft_Azure_CostManagement/Menu/~/overview',+ verbs: ['voice', 'tts'],+ checkKey(key) { placed(key); },+ async run(verb, args, ctx) {+ const { region, key } = placed(ctx.key);+ const base = serviceUrl('AZURE', `https://${region}.tts.speech.microsoft.com`);+ const send = (/** @type {string} */ path, /** @type {RequestInit} */ init = {}) =>+ call(NAME, `${base}/cognitiveservices${path}`, { ...init, headers: { 'ocp-apim-subscription-key': key, 'user-agent': 'openfilm', ...init.headers } }, ctx);++ if (verb === 'voice') {+ const limit = clamp(Math.round(number(args.limit) ?? 5), 1, 100);+ const language = text(args.language).toLowerCase();+ const gender = text(args.gender).toLowerCase().slice(0, 1);+ const prompt = text(args.prompt).toLowerCase();+ const all = /** @type {any[]} */ (await (await send('/voices/list')).json());+ const said = [];+ const match = (/** @type {any} */ v) => [v.ShortName, v.DisplayName, v.LocalName, v.LocaleName, ...(Array.isArray(v.StyleList) ? v.StyleList : [])]+ .some((field) => text(field).toLowerCase().includes(prompt));+ let found = (Array.isArray(all) ? all : []).filter((v) => !prompt || match(v));+ if (prompt && !found.length) {+ found = Array.isArray(all) ? all : [];+ said.push(`no voice matched "${prompt}"; these are others`);+ }+ const list = found.map((v) => {+ const sex = text(v.Gender).toLowerCase();+ const styles = Array.isArray(v.StyleList) ? v.StyleList.map(text).filter(Boolean) : [];+ return {+ voiceId: text(v.ShortName),+ name: text(v.DisplayName) || text(v.LocalName),+ language: text(v.Locale) || null,+ gender: sex === 'male' ? 'm' : sex === 'female' ? 'f' : null,+ description: [text(v.LocaleName), styles.length ? `styles: ${styles.join(', ')}` : ''].filter(Boolean).join(' · ') || null,+ };+ }).filter((v) => v.voiceId+ && (!language || (v.language ?? '').toLowerCase().startsWith(language))+ && (!gender || v.gender === gender));+ return { files: [], index: [], receipt: { provider: 'azure', voices: list.slice(0, limit), ...notes(said) } };+ }+ if (verb === 'tts') {+ const voice = needed(args, 'voice');+ const said = needed(args, 'text');+ const path = landing('audio/vo', args.out, 'wav');+ /* the voice's own locale (en-US-AvaNeural → en-US) tells the service how to read numbers and names */+ const lang = /^[a-z]{2,3}-[A-Za-z0-9]+/.exec(voice)?.[0] ?? 'en-US';+ const ssml = `<speak version='1.0' xml:lang='${lang}'><voice name='${xml(voice)}'>${xml(said)}</voice></speak>`;+ const res = await send('/v1', { method: 'POST', headers: { 'content-type': 'application/ssml+xml', 'x-microsoft-outputformat': FORMAT }, body: ssml });+ const bytes = new Uint8Array(await res.arrayBuffer());+ const dur = wavSeconds(bytes);+ return {+ files: [{ path, bytes }],+ index: [{ src: path, kind: 'audio', ...(dur !== null ? { dur } : {}), text: said, voice, from: { mode: 'synth', text: said, voice, provider: 'azure' } }],+ receipt: { provider: 'azure', src: path, dur, voice, notes: ['Azure gives no word timings: subtitles spread the text over the line'] },+ cost: billedBy(NAME),+ };+ }+ throw new Error(`${NAME} does not do ${verb}.`);+ },+};diff --git a/packages/openfilm/studio/server/providers/azure.test.mjs b/packages/openfilm/studio/server/providers/azure.test.mjsnew file mode 100644index 0000000..8832f4e--- /dev/null+++ b/packages/openfilm/studio/server/providers/azure.test.mjs@@ -0,0 +1,105 @@+import { test, before, after } from 'node:test';+import assert from 'node:assert/strict';+import { createServer } from 'node:http';+import azure from './azure.mjs';+import { wav } from './common.mjs';++const KEY = 'eastus:azure-test-0123456789abcdef';+/** A fake Azure Speech on 127.0.0.1: `reply` answers each request; `seen` keeps them. */+let server;+let reply = () => [404, {}];+const seen = [];++before(async () => {+ server = createServer(async (req, res) => {+ const chunks = [];+ 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 (body instanceof Uint8Array) res.writeHead(status, { 'content-type': 'audio/wav' }).end(body);+ else res.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(body));+ });+ await new Promise((done) => server.listen(0, '127.0.0.1', done));+ process.env.OPENFILM_AZURE_URL = `http://127.0.0.1:${server.address().port}`;+ delete process.env.AZURE_SPEECH_REGION;+});+after(() => server.close());++const ctx = (key = KEY) => ({ key, root: '/project', signal: new AbortController().signal, say: () => {}, read: async () => undefined });++const VOICES = [+ { ShortName: 'en-US-AvaMultilingualNeural', DisplayName: 'Ava Multilingual', LocalName: 'Ava', Gender: 'Female', Locale: 'en-US', LocaleName: 'English (United States)', StyleList: ['cheerful'] },+ { ShortName: 'en-US-AndrewNeural', DisplayName: 'Andrew', LocalName: 'Andrew', Gender: 'Male', Locale: 'en-US', LocaleName: 'English (United States)' },+ { ShortName: 'zh-CN-XiaoxiaoNeural', DisplayName: 'Xiaoxiao', LocalName: '晓晓', Gender: 'Female', Locale: 'zh-CN', LocaleName: 'Chinese (Mainland)', StyleList: ['newscast', 'sad'] },+];++test('voice-over: SSML in the voice\'s locale, as WAV, its length from the file; the key and region split apart', async () => {+ reply = () => [200, wav(new Uint8Array(48000), 24000)];+ const result = await azure.run('tts', { out: 'line', text: "Mix & master, <fast>.", voice: 'zh-CN-XiaoxiaoNeural' }, ctx());+ const call = seen.at(-1);+ assert.equal(call.url.pathname, '/cognitiveservices/v1');+ assert.equal(call.headers['ocp-apim-subscription-key'], 'azure-test-0123456789abcdef');+ assert.equal(call.headers['x-microsoft-outputformat'], 'riff-24khz-16bit-mono-pcm');+ assert.equal(call.headers['content-type'], 'application/ssml+xml');+ assert.equal(call.body.toString(),+ "<speak version='1.0' xml:lang='zh-CN'><voice name='zh-CN-XiaoxiaoNeural'>Mix & master, <fast>.</voice></speak>");+ assert.equal(result.files[0].path, 'assets/audio/vo/line.wav');+ assert.equal(result.index[0].dur, 1);+ assert.equal(result.index[0].words, undefined);+ assert.match(result.receipt.notes[0], /no word timings/);+ assert.equal(result.cost.note, 'billed by Azure Speech to your key');+});++test('a key without a region is refused before anything is sent, unless AZURE_SPEECH_REGION says it', async () => {+ const before = seen.length;+ await assert.rejects(azure.run('tts', { out: 'x', text: 'Hi.', voice: 'en-US-AndrewNeural' }, ctx('azure-test-0123456789abcdef')), /region/);+ assert.equal(seen.length, before);+ reply = () => [200, wav(new Uint8Array(24000), 24000)];+ process.env.AZURE_SPEECH_REGION = 'westus2';+ try {+ const result = await azure.run('tts', { out: 'x', text: 'Hi.', voice: 'en-US-AndrewNeural' }, ctx('azure-test-0123456789abcdef'));+ assert.equal(result.index[0].dur, 0.5);+ assert.equal(seen.at(-1).headers['ocp-apim-subscription-key'], 'azure-test-0123456789abcdef');+ } finally {+ delete process.env.AZURE_SPEECH_REGION;+ }+});++test('a region that could not be a host name is refused before anything is sent', async () => {+ const before = seen.length;+ process.env.AZURE_SPEECH_REGION = 'east us.evil.example';+ try {+ await assert.rejects(azure.run('tts', { out: 'x', text: 'Hi.', voice: 'en-US-AndrewNeural' }, ctx('azure-test-0123456789abcdef')), /AZURE_SPEECH_REGION does not look like an Azure region/);+ } finally {+ delete process.env.AZURE_SPEECH_REGION;+ }+ assert.equal(seen.length, before);+});++test('checkKey holds a pasted key to the same rule, so Settings refuses one that cannot work', () => {+ assert.throws(() => azure.checkKey('azure-test-0123456789abcdef'), /region/);+ azure.checkKey(KEY);+ process.env.AZURE_SPEECH_REGION = 'westus2';+ try {+ azure.checkKey('azure-test-0123456789abcdef');+ } finally {+ delete process.env.AZURE_SPEECH_REGION;+ }+});++test('voices: the service\'s list, searched by the prompt, then by language and gender', async () => {+ reply = () => [200, VOICES];+ const women = await azure.run('voice', { language: 'en', gender: 'f' }, ctx());+ assert.equal(seen.at(-1).url.pathname, '/cognitiveservices/voices/list');+ assert.deepEqual(women.receipt.voices, [{+ voiceId: 'en-US-AvaMultilingualNeural', name: 'Ava Multilingual', language: 'en-US', gender: 'f',+ description: 'English (United States) · styles: cheerful',+ }]);+ const searched = await azure.run('voice', { prompt: '晓晓' }, ctx());+ assert.deepEqual(searched.receipt.voices.map((v) => v.voiceId), ['zh-CN-XiaoxiaoNeural']);+ assert.equal(searched.receipt.notes, undefined);+ const missed = await azure.run('voice', { prompt: 'yodeling', limit: 2 }, ctx());+ assert.deepEqual(missed.receipt.voices.map((v) => v.voiceId), ['en-US-AvaMultilingualNeural', 'en-US-AndrewNeural']);+ assert.match(missed.receipt.notes[0], /no voice matched "yodeling"/);+});diff --git a/packages/openfilm/studio/server/providers/contract.mjs b/packages/openfilm/studio/server/providers/contract.mjsindex 6d11cef..73ea2b5 100644--- a/packages/openfilm/studio/server/providers/contract.mjs+++ b/packages/openfilm/studio/server/providers/contract.mjs@@ -77,10 +77,13 @@* billingUrl: string,* verbs: Verb[],* models?: Partial<Record<Verb, { id: string, name: string }[]>>,+ * checkKey?: (key: string) => void,* 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* (Settings → Models shows "ElevenLabs · Multilingual v2").+ * `checkKey`: throws a sentence when a pasted key cannot work as it is (Azure's must carry its region), shown where it+ * is pasted instead of at the first run. Only for what the provider knows without calling anyone: it must not fetch.* `billingUrl`: the provider's own page where the person tops up its balance. A run that fails because the account has* no balance left throws an Error with `code: 'balance'` (common.mjs `noBalance`), the same for every provider: the* person is told in Studio, with this page, and the agent is told to stop.diff --git a/packages/openfilm/studio/server/providers/index.mjs b/packages/openfilm/studio/server/providers/index.mjsindex 6a0107c..8a7d96a 100644--- a/packages/openfilm/studio/server/providers/index.mjs+++ b/packages/openfilm/studio/server/providers/index.mjs@@ -2,8 +2,8 @@/*** Which provider serves each verb of `openfilm get`, and the API of Studio's Settings → Providers and Models.*- * A person's own key for ElevenLabs, OpenAI, Google (the Gemini API), fal.ai, Groq, Pexels, Pixabay, Brave Search or- * Tavily pays that service directly for what it can do. Each makes a kind of media with the model the person chose for+ * A person's own key for ElevenLabs, OpenAI, Google (the Gemini API), fal.ai, Groq, Azure Speech, Pexels, Pixabay,+ * Brave Search or Tavily pays that service directly for what it can do. Each makes a kind of media with the model the person chose for* it (the provider's first unless they did).* Who serves a verb: `--via <provider>` on the command, else the person's choice for that kind of media in Settings (`use`),* while it can; else nothing does. Every provider is treated alike: a kind with no choice goes to the first provider,@@ -23,6 +23,7 @@ import pixabay from './pixabay.mjs';import brave from './brave.mjs';import tavily from './tavily.mjs';import groq from './groq.mjs';+import azure from './azure.mjs';/*** @typedef {import('./contract.mjs').Provider} Provider @typedef {import('./contract.mjs').Verb} Verb@@ -31,7 +32,7 @@ import groq from './groq.mjs';*//** The providers paid with the person's own key. */-const OWN = [elevenlabs, openai, google, fal, pexels, pixabay, brave, tavily, groq];+const OWN = [elevenlabs, openai, google, fal, pexels, pixabay, brave, tavily, groq, azure];/** 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']);@@ -140,7 +141,7 @@ export async function providersRoute(req, res, parts, { openBrowser }) {return json(res, 200, await state());}let key;- try { key = cleanKey(body.key); } catch (e) { throw new HttpError(400, /** @type {Error} */ (e).message); }+ try { key = cleanKey(body.key); provider.checkKey?.(key); } catch (e) { throw new HttpError(400, /** @type {Error} */ (e).message); }await changeSettings((s) => { s.keys[provider.id] = key; on(s); fill(s); });return json(res, 200, await state());}diff --git a/packages/openfilm/studio/server/providers/index.test.mjs b/packages/openfilm/studio/server/providers/index.test.mjsindex e4ad8c1..e66d514 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 } 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']) 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']) 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']);+ assert.deepEqual(listProviders().map((p) => p.id), ['elevenlabs', 'openai', 'google', 'fal', 'pexels', 'pixabay', 'brave', 'tavily', 'groq', 'azure']);});test('nothing serves a kind of media nobody chose, even with a key that could', async () => {