Open source CapCut alternative.
TypeScript
fix(site): voiceovers carry their spoken language into transcription
David Le7ac7c0758071
diff --git a/site/src/cut/lib/genvideo/adapters/transcribe.ts b/site/src/cut/lib/genvideo/adapters/transcribe.tsindex 911c971d..7140d4fc 100644--- a/site/src/cut/lib/genvideo/adapters/transcribe.ts+++ b/site/src/cut/lib/genvideo/adapters/transcribe.ts@@ -12,16 +12,23 @@*/import { runTranscription, useEditor } from "../../store";+import { trackLocale } from "../../subtitles";import type { TranscribeRole } from "../capabilities";import type { TranscriptWord } from "../types";export function makeTranscribeRole(projectId: string): TranscribeRole {return {async transcribe(audioMediaId) {- const asset = useEditor.getState().assets.find((a) => a.id === audioMediaId);+ const state = useEditor.getState();+ const asset = state.assets.find((a) => a.id === audioMediaId);if (!asset || asset.type !== "audio") throw new Error("No audio to transcribe.");const cues = await runTranscription(projectId, {duration: asset.duration,+ // The recognizer's language: a voiceover stamped what it speaks at+ // synthesis; imported audio falls back to the project's subtitle+ // language. The wrong recognizer romanizes the words into garbage and+ // the whole plan downstream depicts that garbage.+ locale: asset.language ?? trackLocale(state.subtitles, state.subtitleLane),clips: [],audio: [{ file: asset.fileName, in: 0, out: asset.duration, start: 0, volume: 1 }],});diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 216e9d7f..5eb402a5 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -2341,7 +2341,7 @@ useEditor.subscribe((s, prev) => {* writes, and the one its change detector compares (runtime fields like* thumbs/peaks must not mark the doc dirty). */export function storedAssets(assets: MediaAsset[]): StoredAsset[] {- return assets.map(({ id, fileName, name, type, duration, width, height, origin, chatId }) => ({+ return assets.map(({ id, fileName, name, type, duration, width, height, origin, chatId, language }) => ({id,fileName,name,@@ -2351,6 +2351,7 @@ export function storedAssets(assets: MediaAsset[]): StoredAsset[] {...(height !== undefined ? { height } : {}),...(origin !== undefined ? { origin } : {}),...(chatId !== undefined ? { chatId } : {}),+ ...(language !== undefined ? { language } : {}),}));}diff --git a/site/src/cut/lib/tts.ts b/site/src/cut/lib/tts.tsindex 0701bb65..a19c7e87 100644--- a/site/src/cut/lib/tts.ts+++ b/site/src/cut/lib/tts.ts@@ -2,6 +2,7 @@import { geminiModels } from "@/lib/inference/gemini-models";import { bytesFromBase64 } from "./bytes";+import { hostedPost } from "./hosted";import { useGenNotify } from "./genNotify";import { importFileToProject } from "./media";import type { MediaAsset } from "./types";@@ -87,8 +88,6 @@ export function resolveLanguage(wanted?: string): string {return bare?.id ?? DEFAULT_LANGUAGE;}-const CLIENT_ID = "donkey-cut";-/** What a free-text voice direction resolves to once a model has read it. */export interface VoiceoverPlan {/** Lines to speak, in order — translated into `language` when the direction@@ -134,15 +133,11 @@ export async function planVoiceover(const passthrough: VoiceoverPlan = { texts, direction, language: opts.language };if (!direction) return passthrough;try {- const res = await fetch("/api/inference/responses", {- method: "POST",- headers: { "Content-Type": "application/json", "x-donkey-client-id": CLIENT_ID },- body: JSON.stringify({- donkeyProvider: "gemini",- model: geminiModels.flash,- instructions: PLAN_INSTRUCTIONS,- input: [{ role: "user", content: [{ text: JSON.stringify({ direction, lines: texts }) }] }],- }),+ const res = await hostedPost("/api/inference/responses", {+ donkeyProvider: "gemini",+ model: geminiModels.flash,+ instructions: PLAN_INSTRUCTIONS,+ input: [{ role: "user", content: [{ text: JSON.stringify({ direction, lines: texts }) }] }],});if (!res.ok) return passthrough;const body = (await res.json()) as { output_text?: string };@@ -226,17 +221,13 @@ async function synthesizeSegment(): Promise<PcmClip> {const style = direction?.trim();const languageCode = resolveLanguage(language);- const res = await fetch("/api/inference/assets", {- method: "POST",- headers: { "Content-Type": "application/json", "x-donkey-client-id": CLIENT_ID },- body: JSON.stringify({- kind: "speech",- prompt: style ? `${style}: ${text}` : text,- inputs: { voice },- ...(languageCode !== DEFAULT_LANGUAGE- ? { parameters: { languageCode } }- : {}),- }),+ const res = await hostedPost("/api/inference/assets", {+ kind: "speech",+ prompt: style ? `${style}: ${text}` : text,+ inputs: { voice },+ ...(languageCode !== DEFAULT_LANGUAGE+ ? { parameters: { languageCode } }+ : {}),});if (!res.ok) {const message = await readError(res, "Voice generation failed.");@@ -323,10 +314,35 @@ export interface SpeechLayout {* readout, and the in-panel preview — so language handling is identical* everywhere.*/+/** The locale a text will be SPOKEN in, read from its writing system. For a+ * non-Latin script the letters are definitive — Hangul speaks Korean whatever+ * any language picker says. Latin scripts can't be told apart this way, so+ * they return undefined and the planned/picked language decides. */+export function scriptSpokenLocale(text: string): string | undefined {+ const scripts: [RegExp, string][] = [+ [/[-ヿ]/gu, "ja-JP"], // kana first: Japanese also uses Han+ [/[가-ᄀ-ᇿ-]/gu, "ko-KR"],+ [/[一-鿿]/gu, "zh-CN"],+ [/[Ѐ-ӿ]/gu, "ru-RU"],+ [/[-ۿ]/gu, "ar-SA"],+ [/[-]/gu, "he-IL"],+ [/[-]/gu, "th-TH"],+ [/[ऀ-ॿ]/gu, "hi-IN"],+ [/[Ͱ-Ͽ]/gu, "el-GR"],+ ];+ const letters = (text.match(/\p{L}/gu) ?? []).length;+ if (letters === 0) return undefined;+ for (const [re, locale] of scripts) {+ const count = (text.match(re) ?? []).length;+ if (count >= 4 && count / letters >= 0.2) return locale;+ }+ return undefined;+}+export async function renderSpeechClip(segments: SpeechSegment[],opts: { voice: string; direction?: string; language?: string }-): Promise<{ blob: Blob; offset: number; layout: SpeechLayout[] }> {+): Promise<{ blob: Blob; offset: number; layout: SpeechLayout[]; language?: string }> {const raw = segments.map((s) => ({ text: s.text.trim(), at: Math.max(0, s.at) })).filter((s) => s.text);@@ -400,7 +416,12 @@ export async function renderSpeechClip(at: offset + placed[i],duration: clips[i].samples.length / clips[i].rate,}));- return { blob, offset, layout };+ // What the clip actually speaks — its writing system first (definitive for+ // non-Latin scripts), then the direction's ask, then the picked language.+ // Stamped on the asset so transcription later runs the right recognizer.+ const language =+ scriptSpokenLocale(lines.map((l) => l.text).join(" ")) ?? plan.language ?? opts.language;+ return { blob, offset, layout, ...(language ? { language } : {}) };}/** Save a rendered speech clip into the project's media folder as a voiceover@@ -409,7 +430,8 @@ export async function renderSpeechClip(export async function speechClipToAsset(projectId: string,blob: Blob,- name?: string+ name?: string,+ language?: string): Promise<MediaAsset> {const label = name?.trim() || "AI voice";const file = new File([blob], `${slug(label)}.wav`, { type: "audio/wav" });@@ -417,6 +439,7 @@ export async function speechClipToAsset(if (!asset) throw new Error("Could not save the voiceover into the project.");asset.name = label;asset.origin = "voiceover";+ if (language) asset.language = language;// Every committed voiceover funnels through here (the panel, the subtitles// readout, the AI tool), so this is where a finished one gets its badge.useGenNotify.getState().landed("audio", asset.id);@@ -431,8 +454,8 @@ export async function synthesizeSpeech(segments: SpeechSegment[],opts: { voice: string; direction?: string; language?: string; name?: string }): Promise<{ asset: MediaAsset; offset: number; layout: SpeechLayout[] }> {- const { blob, offset, layout } = await renderSpeechClip(segments, opts);- const asset = await speechClipToAsset(projectId, blob, opts.name);+ const { blob, offset, layout, language } = await renderSpeechClip(segments, opts);+ const asset = await speechClipToAsset(projectId, blob, opts.name, language);return { asset, offset, layout };}diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex 99b52f66..d35874f6 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -34,6 +34,9 @@ export interface StoredAsset {* Cut created or fetched — it lives where it was made (the timeline, a* generation panel, or an AI chat card) and is kept out of the Media panel. */origin?: "voiceover" | "generated" | "recording" | "stock" | "freeze" | "chat";+ /** BCP-47 of the audio's spoken language, when known (stamped on voiceovers+ * at synthesis) — what transcription should run its recognizer in. */+ language?: string;/** For origin "chat": the chat thread that made it. Deleting that thread* deletes the assets it still owns (see chatAssets.ts). */chatId?: string;diff --git a/site/src/cut/lib/voiceover.ts b/site/src/cut/lib/voiceover.tsindex 46d6d839..d5775375 100644--- a/site/src/cut/lib/voiceover.ts+++ b/site/src/cut/lib/voiceover.ts@@ -27,7 +27,7 @@ function readoutCues(cueIds?: string[]): ReadoutCue[] {// preview the user liked becomes the exact clip that lands on the timeline// instead of a second (paid) synthesis. Keyed by everything that changes the// audio, so any edit re-renders.-let cached: { sig: string; blob: Blob; offset: number; layout: SpeechLayout[] } | null = null;+let cached: { sig: string; blob: Blob; offset: number; layout: SpeechLayout[]; language?: string } | null = null;function signature(voice: string,@@ -49,11 +49,11 @@ async function renderReadout() {const sig = signature(voice, cues, opts);if (cached?.sig === sig) return cached;- const { blob, offset, layout } = await renderSpeechClip(+ const { blob, offset, layout, language } = await renderSpeechClip(cues.map((c) => ({ text: c.text, at: c.start })),{ voice, direction: opts?.direction, language: opts?.language });- cached = { sig, blob, offset, layout };+ cached = { sig, blob, offset, layout, language };return cached;}@@ -74,8 +74,8 @@ export async function generateSubtitlesReadout(const cues = readoutCues(opts?.cueIds);if (cues.length === 0) throw new Error("No subtitles to read.");- const { blob, offset, layout } = await renderReadout(voice, cues, opts);- const asset = await speechClipToAsset(projectId, blob, "Subtitles readout");+ const { blob, offset, layout, language } = await renderReadout(voice, cues, opts);+ const asset = await speechClipToAsset(projectId, blob, "Subtitles readout", language);const duck = opts?.duck ?? DUCK_DEFAULT;const cur = useEditor.getState();cur.addAsset(asset);