Drive Google Flow from Claude, Codex or a local control panel, on Mac or Windows — using your Google AI subscription credits instead of the pay-per-use video API. No browser extension.
Captions in about 100 languages: language picker, detection, the right model per language
GTAI-1f4f6d705d37d
diff --git a/CLAUDE.md b/CLAUDE.mdindex 6566da3..6edf130 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -484,3 +484,19 @@ The preview tool could not read the project while it lived in ~/Desktop; check tmoment. The voice track is written as PCM WAV: AAC .m4a from delayed+mixed lines was unreadable ("Cannot calculatedts entry length"), and whisper-cli exits 0 and writes no JSON on unreadable audio, so transcribe now checks for it.Cut lines at the gap between words (midpoint), not word end + padding: padding pulled the next word's start in.+- CAPTION LANGUAGES (2026-10-13): the auto-downloaded model was English-only (base.en) and "auto" picked it, so a+ Spanish video got English-sounding nonsense with no error ("(speaking in foreign language)" at best). Now three+ models, each fetched on first need (FLOW_MCP_MODEL_BASE = mirror folder): base.en 148 MB for English (best timing;+ English fetches it even when a multilingual model exists, falling back to that one only if the download fails),+ large-v3-turbo-q5_0 574 MB for every other language, and base-q5_1 60 MB that only DETECTS the language for "auto"+ (whisper-cli -dl; the line "auto-detected language: xx" is on stderr and -np hides it). Measured on Mac `say` lines:+ turbo heard every Spanish/German word where small-q5_1 (190 MB) misheard "ni un solo" -> "guión solo"; word starts+ of both were within ~0.05 s of the waveform for most words; base-q5_1 detected 8/8 languages in 0.2 s. Detection+ runs once per video ("auto" has its own cache entry). UNSPACED languages (ja, zh, yue, th...) get words from+ Intl.Segmenter over a per-character timeline built from the tokens (tokens there are word pieces: 人/工/知/能), are+ joined with no space, hold 3x the words per caption and count as full-width; edited text is segmented the same way+ so alignText still matches. <html lang> is set so capitals follow the language (Turkish BİRLİKTE), RTL scripts get+ dir=rtl (checked with Arabic text: order and highlight right). The panel has a "Spoken language" select (37 languages+ + Detect automatically), defaulting to the browser's language when listed, else English; changing it re-listens and+ drops corrections. The panel read transcribe's `words` (now an array since flow_transcribe) as the word count; it+ now asks words:false and shows word_count.diff --git a/OVERVIEW.md b/OVERVIEW.mdindex 300364b..af6e6b8 100644--- a/OVERVIEW.md+++ b/OVERVIEW.md@@ -106,7 +106,7 @@ This is a limit in Flow itself, not something we can program around. The exact j|---|---|| **Voiceover Recorder** | Narration for free, at any length. Either Google AI Studio's text-to-speech (the same voices Flow has, and you can tell it *how* to read the line; keep that note short) or a voice already on your computer (macOS voices on a Mac, Windows' own voices on a PC) || **Voice List** | Every narrator available to you |-| **Captions** | Puts the spoken words on screen, the way short-form videos do, on wide or vertical videos. Your computer listens to the video with whisper.cpp, a free speech-to-text program, and times every word itself; nothing is uploaded. Five styles: big capitals where the word being said lights up, a coloured block behind the word being said, words appearing as they're said, classic subtitles, and white words on a dark band. Each can use normal letters, ALL CAPITALS or all lowercase. Also writes a subtitle file for YouTube |+| **Captions** | Puts the spoken words on screen, the way short-form videos do, on wide or vertical videos. Your computer listens to the video with whisper.cpp, a free speech-to-text program, and times every word itself; nothing is uploaded. Five styles: big capitals where the word being said lights up, a coloured block behind the word being said, words appearing as they're said, classic subtitles, and white words on a dark band. Each can use normal letters, ALL CAPITALS or all lowercase. Works in about 100 languages, including Japanese and Chinese (written without spaces) and Arabic and Hebrew (right to left). Also writes a subtitle file for YouTube || **Word Finder** | Listens to any video or audio on your computer and writes down every word with the moment it is said. Free, nothing uploaded. Used to check a voice take said the right words, and to cut it into lines || **Film Cutter** | Joins clips into one film using FFmpeg, a free video toolkit: the clips you made, or any video you pick, in the order you choose. Lays the narration on top, adds a looping music bed, and lets you turn the clips' own sound down so it doesn't drown out the voice. Sizes everything to match your best clip, and can hold the last frame if the voice runs longer than the footage. A narration can also be placed line by line, so each sentence lands exactly when its title appears |@@ -125,7 +125,7 @@ Eight tabs, in the order you'd use them:4. **Voice**: record the narration, free. Your saved narrations are listed here, so you can play them back or delete the ones you don't want. This is also where you paste your free Google AI Studio key. It's checked with Google and saved only on your computer, so you never have to put it in a chat5. **Restyle**: change a clip you already have6. **Cut**: join everything into a finished film. Pick the videos you want, in order (ones you made, or any video you upload), then add a narration and music, and turn the clips' own sound down so the voice sits on top-7. **Captions**: put the words on screen. Pick a video and a style, choose where the words sit (bottom, middle, top, or tap the preview to put them exactly where you want), how big they are, normal, capital or lowercase letters, and the highlight colour, and you see the result on a real frame of your video before making it. If the computer misheard a word, fix it in the text and the timing stays right; press Enter wherever you want a new caption to start. The first time you pick a video, it downloads a free speech model by itself (148 MB, once)+7. **Captions**: put the words on screen. Pick a video, the language spoken in it (or let it work that out) and a style, choose where the words sit (bottom, middle, top, or tap the preview to put them exactly where you want), how big they are, normal, capital or lowercase letters, and the highlight colour, and you see the result on a real frame of your video before making it. If the computer misheard a word, fix it in the text and the timing stays right; press Enter wherever you want a new caption to start. The first time you pick a video, it downloads a free speech model by itself, once: 148 MB for English, 574 MB for any other language8. **Library**: browse what Flow is holding, pull it back for free, or move things to Flow's TrashProgress and a gallery of your saved work sit alongside. The gallery shows stills or clips on the tabs where you'd use them, and on a wide screen each side scrolls on its own.diff --git a/README.md b/README.mdindex 7996653..e345508 100644--- a/README.md+++ b/README.md@@ -27,7 +27,7 @@ New here? [GETTING-STARTED.md](GETTING-STARTED.md) takes you from nothing to you| **A Google account** | Free. Flow gives every account 50 credits a day; a paid Google AI plan adds more and unlocks 1080p downloads. Developed on a Pro plan || **FFmpeg** *(optional)* | Mac: `brew install ffmpeg` · Windows: `winget install Gyan.FFmpeg`. Needed only to join clips, mix music or record narration || **A Google AI Studio key** *(optional, free)* | Only for the Google narration voices. See below |-| **whisper.cpp** *(optional, free)* | Only for captions: it hears the words, on your computer. Mac: `brew install whisper-cpp` · Windows: `whisper-cli.exe` from [the whisper.cpp releases](https://github.com/ggml-org/whisper.cpp/releases), on your PATH. The speech model it needs (148 MB) downloads by itself the first time you caption a video |+| **whisper.cpp** *(optional, free)* | Only for captions: it hears the words, on your computer. Mac: `brew install whisper-cpp` · Windows: `whisper-cli.exe` from [the whisper.cpp releases](https://github.com/ggml-org/whisper.cpp/releases), on your PATH. The speech model it needs downloads by itself the first time you caption a video: 148 MB for English, 574 MB for any other language |A display must stay awake: the Chrome window is really being driven, so the machine cannot beheadless or asleep mid-run.@@ -158,7 +158,8 @@ Eight tabs, in the order you would use them:already made. Add a narration (from your saved ones or an upload) and music, and turn the clips' ownsound down so the narration sits on top.- **Captions**: put the spoken words on screen, the way short-form videos do, on wide or vertical videos.- Pick a video, choose a style (Bold pop, Highlight, Word by word, Clean, Boxed), where it sits (bottom,+ Pick a video and the language spoken in it (about 100 languages, or Detect automatically), choose a+ style (Bold pop, Highlight, Word by word, Clean, Boxed), where it sits (bottom,middle, top, an exact height, or tap the preview), its size (a slider), its letters (normal, CAPS or lowercase) andhighlight colour, and see it on a real frame of your video before anything is made. Fix any misheardword in the text box and it keeps its timing; press Enter to start a new caption. Saves `<name>-captions.mp4` plus an `.srt` for YouTube.@@ -203,7 +204,7 @@ agree on what is running. That API listens on 127.0.0.1 only and needs a per-run| `flow_techniques` | 39 film-technique prompt presets (camera moves, product shots, transitions, image commands); pass an id as a scene's `technique` || `flow_narrate` | Free narration audio, any length: `gemini` (Google AI Studio text-to-speech, with the same voices Flow has, plus a `style` note) or `mac` (a voice installed on this computer, no key needed) || `flow_voices` | Narrator voices available, and whether a Google key is set up |-| `flow_captions` | Burn spoken-word captions into any video, landscape or vertical, in one of five styles, at any height and size, in normal, capital or lowercase letters; returns the transcript so a misheard word can be fixed and the call repeated (local whisper.cpp, Chrome and FFmpeg, no credits) |+| `flow_captions` | Burn spoken-word captions into any video, landscape or vertical, in one of five styles, at any height and size, in normal, capital or lowercase letters, in about 100 languages; returns the transcript so a misheard word can be fixed and the call repeated (local whisper.cpp, Chrome and FFmpeg, no credits) || `flow_transcribe` | Hear the words in any video or audio on your computer, with each word's start and end time (local whisper.cpp, free) || `flow_assemble` | Join clips into one MP4 (a project's clips, or any you list, in order) with optional music and voiceover, and separate volume for the clips' own sound. A voiceover can also be built line by line (`voice_lines`), each line cut from a take and placed at its own moment, for narration timed to on-screen titles (local FFmpeg, no credits) |diff --git a/src/captions.ts b/src/captions.tsindex 40dfa04..7f7fa41 100644--- a/src/captions.ts+++ b/src/captions.ts@@ -21,10 +21,24 @@ const WHISPER = process.env.FLOW_MCP_WHISPER ?? "whisper-cli";// Transcripts and preview stills; the panel is allowed to show pictures from here.export const CACHE_DIR = join(HOME_DIR, "captions");const MODEL_DIR = join(HOME_DIR, "models");-// The model fetched on first use: whisper.cpp's own base.en, 148 MB. FLOW_MCP_MODEL_URL points it at a mirror.-const MODEL_NAME = "ggml-base.en.bin";-const MODEL_URL = process.env.FLOW_MCP_MODEL_URL ?? `https://huggingface.co/ggerganov/whisper.cpp/resolve/main/${MODEL_NAME}`;+// Speech models fetched the first time they are needed, from whisper.cpp's own collection on Hugging Face+// (FLOW_MCP_MODEL_BASE points at a mirror folder holding the same files). The sizes are what the panel tells the user.+const SPEECH_MODELS = {+ // English: base.en, an English-only model; those time words best (see PREFERENCE).+ english: { file: "ggml-base.en.bin", mb: 148, purpose: "for English" },+ // Every other language. Measured on Spanish, German, Japanese and Chinese lines (2026-10-13): large-v3-turbo heard+ // every Spanish and German word where small misheard several ("ni un solo" -> "guión solo", "listos" -> "vistos"),+ // placed words as well, and still runs at about ten times real time. q5_0 is its compressed form: the same words at+ // a third of the size.+ other: { file: "ggml-large-v3-turbo-q5_0.bin", mb: 574, purpose: "for this language" },+ // Only names the spoken language, for "auto": right on all 8 test languages in 0.2 s, so an English speaker who never+ // picks a language is not sent the 574 MB model.+ detect: { file: "ggml-base-q5_1.bin", mb: 60, purpose: "that recognises the language" },+} as const;+type SpeechModel = keyof typeof SPEECH_MODELS;+const MODEL_BASE = (process.env.FLOW_MCP_MODEL_BASE ?? "https://huggingface.co/ggerganov/whisper.cpp/resolve/main").replace(/\/+$/, "");const BIG = { maxBuffer: 64 * 1024 * 1024 };+const THREADS = String(Math.max(2, Math.min(8, cpus().length - 1)));type RunError = NodeJS.ErrnoException & { stderr?: string };export interface Word {@@ -70,6 +84,28 @@ export interface CaptionOptions {language?: string;}+// The languages the panel offers, by their own names. whisper.cpp knows about 100; any other code works through the MCP.+export const CAPTION_LANGUAGES = [+ ["en", "English"], ["es", "Español"], ["pt", "Português"], ["fr", "Français"], ["de", "Deutsch"], ["it", "Italiano"],+ ["nl", "Nederlands"], ["tr", "Türkçe"], ["pl", "Polski"], ["ru", "Русский"], ["uk", "Українська"], ["ar", "العربية"],+ ["he", "עברית"], ["fa", "فارسی"], ["hi", "हिन्दी"], ["ur", "اردو"], ["bn", "বাংলা"], ["ta", "தமிழ்"], ["id", "Bahasa Indonesia"],+ ["ms", "Bahasa Melayu"], ["tl", "Filipino"], ["vi", "Tiếng Việt"], ["th", "ไทย"], ["ja", "日本語"], ["zh", "中文"], ["yue", "粵語"],+ ["ko", "한국어"], ["sv", "Svenska"], ["da", "Dansk"], ["no", "Norsk"], ["fi", "Suomi"], ["el", "Ελληνικά"], ["cs", "Čeština"],+ ["ro", "Română"], ["hu", "Magyar"], ["ca", "Català"], ["sw", "Kiswahili"],+].map(([code, name]) => ({ code, name }));+// Written without spaces between words: whisper's tokens are then pieces of words, so words come from the language's+// own word breaker, and they are drawn side by side with no space between them.+const UNSPACED = new Set(["ja", "zh", "yue", "th", "lo", "km", "my", "bo"]);+// Letters about one em wide, far wider than the Latin letters CHAR_EM is measured on.+const FULL_WIDTH = new Set(["ja", "zh", "yue", "ko"]);+const RTL = new Set(["ar", "he", "fa", "ur", "yi", "ps", "sd", "ug"]);+const joiner = (lang: string) => (UNSPACED.has(lang) ? "" : " ");+// Punctuation that opens a word (¿Qué, «Hola, 「はい) and punctuation that ends one or a sentence, in many scripts.+const OPENER = /^[¿¡«“„‘‚(\[{「『(《〈]+$/;+const CLOSER = /^[.,!?;:%)\]}"'»…\-。、,!?;:)」』》〉”’،؛؟।]/;+const SENTENCE_END = /[.!?…。!?؟।]["')\]」』)”’]*$/;+const CLAUSE_END = /[,;:,、;:،؛]$/;+const lettersOf = (o: { style: CaptionStyle; letters?: CaptionLetters }): CaptionLetters => o.letters ?? CAPTION_STYLES[o.style].letters;// Letter size as a share of the frame's short side, so a 9:16 phone video and a 16:9 landscape one read the same.@@ -86,30 +122,31 @@ const LEAD = 0.12;/* ---------- hearing the words ---------- */-const MODEL_PREFERENCE = [- // English-only models time words best. large-v3-turbo is the most accurate listener but placed "picks" 0.6 s- // early in a test where small.en was 30 ms out, so it comes last.- "ggml-small.en.bin",- "ggml-base.en.bin",- "ggml-medium.en.bin",- "ggml-small.bin",- "ggml-base.bin",- "ggml-medium.bin",- "ggml-large-v3-turbo.bin",- "ggml-large-v3.bin",-];--class NoModel extends Error {}--function findModel(language: string): string {+const MODEL_DIRS = [MODEL_DIR, join(homedir(), ".cache", "whisper-models"), join(homedir(), ".cache", "whisper.cpp")];+const PREFERENCE: Record<SpeechModel, string[]> = {+ // English-only models time words best. large-v3-turbo is the most accurate listener but placed "picks" 0.6 s early+ // in an English test where small.en was 30 ms out, so for English it is only a fallback.+ english: ["ggml-small.en.bin", "ggml-base.en.bin", "ggml-medium.en.bin"],+ // For other languages hearing the words right matters most. base and the compressed small are left out on purpose:+ // they mishear too much to caption with, even when present (the language detector is one of them).+ other: ["ggml-large-v3-turbo.bin", "ggml-large-v3-turbo-q5_0.bin", "ggml-large-v3.bin", "ggml-medium.bin", "ggml-small.bin"],+ // Any multilingual model can name the language; the fastest goes first.+ detect: ["ggml-base-q5_1.bin", "ggml-base.bin", "ggml-small-q5_1.bin", "ggml-small.bin", "ggml-large-v3-turbo-q5_0.bin", "ggml-large-v3-turbo.bin", "ggml-medium.bin", "ggml-large-v3.bin"],+};+const installed = (kind: SpeechModel): string | undefined => PREFERENCE[kind].flatMap((name) => MODEL_DIRS.map((d) => join(d, name))).find((p) => existsSync(p));++// The model that hears one language, downloaded the first time it is needed. English gets its own model even when a+// multilingual one is there, for the timing; a multilingual model only stands in when that download fails.+async function modelFor(lang: string): Promise<string> {if (process.env.FLOW_MCP_WHISPER_MODEL) return process.env.FLOW_MCP_WHISPER_MODEL;- const dirs = [MODEL_DIR, join(homedir(), ".cache", "whisper-models"), join(homedir(), ".cache", "whisper.cpp")];- const found = MODEL_PREFERENCE.flatMap((name) => dirs.map((d) => join(d, name))).filter((p) => existsSync(p));- // An English-only model cannot hear another language, so prefer a multilingual one when one is asked for.- const wantOther = language !== "auto" && language !== "en";- const pick = (wantOther ? found.find((p) => !p.includes(".en.")) : undefined) ?? found[0];- if (!pick) throw new NoModel();- return pick;+ if (lang !== "en") return installed("other") ?? fetchModel("other");+ const english = installed("english");+ if (english) return english;+ const other = installed("other");+ return fetchModel("english").catch((err: Error) => {+ if (other) return other;+ throw err;+ });}const WHISPER_HINT = IS_MAC@@ -119,28 +156,37 @@ const WHISPER_HINT = IS_MAC: "install whisper.cpp so whisper-cli is on your PATH";// What the panel needs to know before offering captions, and the fix for whatever is missing.-export async function captionSetup(): Promise<{ ready: boolean; whisper: boolean; whisper_hint?: string; model?: string; models_dir: string }> {+export async function captionSetup(): Promise<{+ ready: boolean;+ whisper: boolean;+ whisper_hint?: string;+ models: Record<SpeechModel, boolean>;+ download_mb: Record<SpeechModel, number>;+ languages: typeof CAPTION_LANGUAGES;+ models_dir: string;+}> {const whisper = await run(WHISPER, ["--help"]).then(() => true,(err: RunError) => err.code !== "ENOENT",);- let model: string | undefined;- try {- model = basename(findModel("auto"));- } catch {- model = undefined;- }- // The model is not a precondition: it downloads itself the first time it is needed.- return { ready: whisper, whisper, whisper_hint: whisper ? undefined : WHISPER_HINT, model, models_dir: MODEL_DIR };+ const forced = Boolean(process.env.FLOW_MCP_WHISPER_MODEL);+ // The models are not a precondition: each downloads itself the first time it is needed. The panel uses these to say+ // how big the wait will be.+ const models = { english: forced || Boolean(installed("english")), other: forced || Boolean(installed("other")), detect: forced || Boolean(installed("detect")) };+ const download_mb = { english: SPEECH_MODELS.english.mb, other: SPEECH_MODELS.other.mb, detect: SPEECH_MODELS.detect.mb };+ return { ready: whisper, whisper, whisper_hint: whisper ? undefined : WHISPER_HINT, models, download_mb, languages: CAPTION_LANGUAGES, models_dir: MODEL_DIR };}// Fetched by itself the first time captions are needed (the user chose this over a button, 2026-10-09). One download// at a time even if the panel and an assistant ask together; written to .part and renamed, so a cut-off download is// never mistaken for a model.-let fetching: Promise<string> | null = null;-function downloadSpeechModel(): Promise<string> {- fetching ??= (async () => {- const dest = join(MODEL_DIR, MODEL_NAME);+const fetching = new Map<SpeechModel, Promise<string>>();+function fetchModel(kind: SpeechModel): Promise<string> {+ const { file, mb, purpose } = SPEECH_MODELS[kind];+ const pending = fetching.get(kind);+ if (pending) return pending;+ const job = (async () => {+ const dest = join(MODEL_DIR, file);if (existsSync(dest)) return dest;mkdirSync(MODEL_DIR, { recursive: true });// curl, not fetch: Node's built-in fetch can crash the whole process on an assertion (undici, "assert(!this.paused)")@@ -148,21 +194,25 @@ function downloadSpeechModel(): Promise<string> {// Claude's connector. curl ships with macOS and Windows 10+, follows the redirect to the download host, and can// only fail itself.const part = `${dest}.part`;- await run("curl", ["-L", "--fail", "--silent", "--show-error", "--connect-timeout", "20", "--retry", "2", "-o", part, MODEL_URL], BIG).catch((err: RunError) => {+ await run("curl", ["-L", "--fail", "--silent", "--show-error", "--connect-timeout", "20", "--retry", "2", "-o", part, `${MODEL_BASE}/${file}`], BIG).catch((err: RunError) => {rmSync(part, { force: true });throw new Error(err.code === "ENOENT" ? "curl is not installed" : String(err.stderr || err.message).trim().split("\n").at(-1));});- const size = statSync(part).size;- if (size < 100_000_000) {+ if (statSync(part).size < mb * 0.9e6) {rmSync(part, { force: true });throw new Error("it arrived incomplete");}renameSync(part, dest);return dest;- })().finally(() => {- fetching = null;- });- return fetching;+ })()+ .catch((e: Error) => {+ throw new Error(+ `Captions need a speech model ${purpose}, downloaded once (${mb} MB), and the download failed: ${e.message}. Check the internet connection and try again, or put ${file} in ${MODEL_DIR} yourself.`,+ );+ })+ .finally(() => fetching.delete(kind));+ fetching.set(kind, job);+ return job;}async function probe(file: string, needPicture = true): Promise<{ width: number; height: number; duration: number; audio?: string }> {@@ -188,63 +238,133 @@ async function probe(file: string, needPicture = true): Promise<{ width: number;return { width, height, duration: Number(data.format.duration ?? 0), audio: data.streams.find((s) => s.codec_type === "audio")?.codec_name };}+interface WhisperJson {+ transcription: { tokens?: { text: string; offsets: { from: number; to: number } }[] }[];+ result?: { language?: string };+}+// whisper.cpp's word-sized segments (-ml 1) run each word into the next, hiding every pause. Its tokens keep the real// gaps, so words are rebuilt from those: a token that starts with a space starts a new word, anything else (", 't")-// belongs to the word before it.-function wordsFromTokens(json: { transcription: { tokens?: { text: string; offsets: { from: number; to: number } }[] }[] }): Word[] {+// belongs to the word before it, and a lone opening mark (¿, «) belongs to the word after it.+function wordsFromTokens(json: WhisperJson, lang: string): Word[] {const words: Word[] = [];- for (const seg of json.transcription) {- for (const t of seg.tokens ?? []) {- if (/^\s*\[_/.test(t.text)) continue;- const clean = t.text.trim();- if (!clean) continue;- const last = words.at(-1);- if (last && (!/^\s/.test(t.text) || /^[.,!?;:%)\]}"'»…-]/.test(clean))) {- last.text += clean;- last.end = t.offsets.to / 1000;- } else words.push({ text: clean, start: t.offsets.from / 1000, end: t.offsets.to / 1000 });+ if (UNSPACED.has(lang)) {+ // Here tokens are pieces of words (人 / 工 / 知 / 能), so each character takes its time from its token and words+ // come from the language's own word breaker: 今日 / は / 人工 / 知能 / を.+ let text = "";+ const at: { start: number; end: number }[] = [];+ for (const seg of json.transcription) {+ for (const t of seg.tokens ?? []) {+ if (/^\s*\[_/.test(t.text)) continue;+ const [from, to] = [t.offsets.from / 1000, t.offsets.to / 1000];+ const chars = [...t.text];+ chars.forEach((c, i) => {+ text += c;+ for (let k = 0; k < c.length; k++) at.push({ start: from + ((to - from) * i) / chars.length, end: from + ((to - from) * (i + 1)) / chars.length });+ });+ }+ text += " ";+ at.push(at.at(-1) ?? { start: 0, end: 0 });+ }+ for (const w of segmentWords(text, lang)) words.push({ text: w.text, start: at[w.from].start, end: at[w.to - 1].end });+ } else {+ let opener = "";+ for (const seg of json.transcription) {+ for (const t of seg.tokens ?? []) {+ if (/^\s*\[_/.test(t.text)) continue;+ const clean = t.text.trim();+ if (!clean) continue;+ const last = words.at(-1);+ if (OPENER.test(clean)) opener += clean;+ else if (last && !opener && (!/^\s/.test(t.text) || CLOSER.test(clean))) {+ last.text += clean;+ last.end = t.offsets.to / 1000;+ } else {+ words.push({ text: opener + clean, start: t.offsets.from / 1000, end: t.offsets.to / 1000 });+ opener = "";+ }+ }}}// Drop what whisper writes for non-speech: [MUSIC], (laughs), ♪.- return words.filter((w) => !/^[[(♪*].*[\])♪*]$|^♪+$/.test(w.text));+ return words.filter((w) => !/^[[(♪*(].*[\])♪*)]$|^♪+$/.test(w.text));}+// Splits text written without spaces into words (Intl.Segmenter knows each language's dictionary), keeping punctuation+// with its word. from/to are positions in the text.+function segmentWords(text: string, lang: string): { text: string; from: number; to: number }[] {+ const out: { text: string; from: number; to: number }[] = [];+ let open: { text: string; from: number } | undefined;+ for (const s of new Intl.Segmenter(lang, { granularity: "word" }).segment(text)) {+ const piece = s.segment.trim();+ if (!piece) continue;+ const to = s.index + s.segment.length;+ const last = out.at(-1);+ if (!s.isWordLike && OPENER.test(piece)) open = { text: (open?.text ?? "") + piece, from: open?.from ?? s.index };+ else if (!s.isWordLike && last && !open) {+ last.text += piece;+ last.to = to;+ } else {+ out.push({ text: (open?.text ?? "") + piece, from: open?.from ?? s.index, to });+ open = undefined;+ }+ }+ return out;+}++// Which language is spoken, from the first 30 seconds.+async function detectLanguage(wav: string): Promise<string> {+ const model = installed("detect") ?? (await fetchModel("detect"));+ const { stdout, stderr } = await run(WHISPER, ["-m", model, "-f", wav, "-l", "auto", "-dl", "-t", THREADS], BIG).catch(whisperFailed);+ const lang = /auto-detected language: ([a-z]+)/.exec(`${stderr}${stdout}`)?.[1];+ if (!lang) throw new Error("Couldn't tell which language is spoken. Pick the language and try again.");+ return lang;+}++function whisperFailed(err: RunError): never {+ if (err.code === "ENOENT") throw new Error(`Captions need whisper.cpp to hear the words. Install it: ${WHISPER_HINT}.`);+ throw new Error(`whisper.cpp could not read the sound: ${String(err.stderr ?? err.message).trim().split("\n").at(-1)}`);+}++// language: a whisper code (en, es, ja...) or "auto", which detects it first.export async function transcribe(video: string, language = "auto"): Promise<Transcript> {const info = await probe(video, false);if (!info.audio) throw new Error(`"${basename(video)}" has no sound, so there are no words to caption.`);- let model: string;- try {- model = findModel(language);- } catch (err) {- if (!(err instanceof NoModel)) throw err;- model = await downloadSpeechModel().catch((e: Error) => {- throw new Error(`Captions need a speech model, downloaded once (148 MB), and the download failed: ${e.message}. Check the internet connection and try again, or put ${MODEL_NAME} in ${MODEL_DIR} yourself.`);- });- }- const lang = basename(model).includes(".en.") ? "en" : language;+ const asked = language.trim().toLowerCase() || "auto";+ if (!/^(auto|[a-z]{2,3})$/.test(asked)) throw new Error(`"${language}" isn't a language code. Use a code such as en, es or ja, or auto.`);const st = statSync(video);- const key = createHash("sha1").update(`${video}|${st.size}|${st.mtimeMs}|${basename(model)}|${lang}`).digest("hex").slice(0, 16);- const cached = join(CACHE_DIR, `${key}.json`);- if (existsSync(cached)) return JSON.parse(readFileSync(cached, "utf8")) as Transcript;+ const cacheFile = (...parts: string[]) => join(CACHE_DIR, `${createHash("sha1").update([video, st.size, st.mtimeMs, ...parts].join("|")).digest("hex").slice(0, 16)}.json`);+ const keep = (t: Transcript, ...files: (string | undefined)[]) => {+ mkdirSync(CACHE_DIR, { recursive: true });+ for (const f of files) if (f) writeFileSync(f, JSON.stringify(t));+ return t;+ };+ // "auto" is remembered on its own, so the language is detected once per video, not on every preview.+ const autoFile = asked === "auto" ? cacheFile("auto") : undefined;+ if (autoFile && existsSync(autoFile)) return JSON.parse(readFileSync(autoFile, "utf8")) as Transcript;const work = mkdtempSync(join(tmpdir(), "flow-captions-"));+ const wav = join(work, "audio.wav");+ const extract = () => run(FFMPEG, ["-v", "error", "-y", "-i", video, "-vn", "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", wav], BIG);try {- const wav = join(work, "audio.wav");- await run(FFMPEG, ["-v", "error", "-y", "-i", video, "-vn", "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", wav], BIG);- const threads = String(Math.max(2, Math.min(8, cpus().length - 1)));- await run(WHISPER, ["-m", model, "-f", wav, "-l", lang, "-t", threads, "-ojf", "-of", join(work, "words"), "-np"], BIG).catch((err: RunError) => {- if (err.code === "ENOENT") throw new Error(`Captions need whisper.cpp to hear the words. Install it: ${WHISPER_HINT}.`);- throw new Error(`whisper.cpp could not read the sound: ${String(err.stderr ?? err.message).trim().split("\n").at(-1)}`);- });+ let lang = asked;+ if (lang === "auto" && !process.env.FLOW_MCP_WHISPER_MODEL) {+ await extract();+ lang = await detectLanguage(wav);+ }+ const model = await modelFor(lang);+ if (basename(model).includes(".en.")) lang = "en";+ const cached = cacheFile(basename(model), lang);+ if (existsSync(cached)) return keep(JSON.parse(readFileSync(cached, "utf8")) as Transcript, autoFile);+ if (!existsSync(wav)) await extract();+ await run(WHISPER, ["-m", model, "-f", wav, "-l", lang, "-t", THREADS, "-ojf", "-of", join(work, "words"), "-np"], BIG).catch(whisperFailed);// whisper-cli exits 0 even when it cannot read the audio, and simply writes nothing.if (!existsSync(join(work, "words.json"))) throw new Error(`whisper.cpp could not read the sound in "${basename(video)}".`);- const json = JSON.parse(readFileSync(join(work, "words.json"), "utf8")) as Parameters<typeof wordsFromTokens>[0] & { result?: { language?: string } };- const words = wordsFromTokens(json);+ const json = JSON.parse(readFileSync(join(work, "words.json"), "utf8")) as WhisperJson;+ const heard = json.result?.language ?? lang;+ const words = wordsFromTokens(json, heard);if (!words.length) throw new Error(`No speech was heard in "${basename(video)}".`);- const out: Transcript = { words, text: words.map((w) => w.text).join(" "), language: json.result?.language ?? lang, model: basename(model) };- mkdirSync(CACHE_DIR, { recursive: true });- writeFileSync(cached, JSON.stringify(out));- return out;+ return keep({ words, text: words.map((w) => w.text).join(joiner(heard)), language: heard, model: basename(model) }, cached, autoFile);} finally {rmSync(work, { recursive: true, force: true });}@@ -256,13 +376,10 @@ const norm = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}']+/gu, "");// Lines up a corrected transcript with the timed one. Every word that still matches keeps its timing; new or changed// words are spread evenly over the gap they fill, so fixing "flo" to "Flow" or adding a missed word just works.-export function alignText(timed: Word[], text: string): Word[] {+export function alignText(timed: Word[], text: string, lang = "en"): Word[] {const toks: { text: string; br: boolean }[] = [];text.split("\n").forEach((line, li) =>- line- .split(/\s+/)- .filter(Boolean)- .forEach((t, i) => toks.push({ text: t, br: li > 0 && i === 0 })),+ (UNSPACED.has(lang) ? segmentWords(line, lang).map((w) => w.text) : line.split(/\s+/).filter(Boolean)).forEach((t, i) => toks.push({ text: t, br: li > 0 && i === 0 })),);if (!toks.length) return [];const a = timed.map((w) => norm(w.text));@@ -321,7 +438,7 @@ interface State {to: number;}-function paginate(words: Word[], maxWords: number, maxChars: number): Word[][] {+function paginate(words: Word[], maxWords: number, maxChars: number, sep: string): Word[][] {const pages: Word[][] = [];let cur: Word[] = [];let chars = 0;@@ -332,8 +449,8 @@ function paginate(words: Word[], maxWords: number, maxChars: number): Word[][] {(w.br ||cur.length >= maxWords ||chars + w.text.length > maxChars ||- /[.!?…]["')\]]*$/.test(prev.text) ||- /[,;:]$/.test(prev.text) ||+ SENTENCE_END.test(prev.text) ||+ CLAUSE_END.test(prev.text) ||w.start - prev.end > 0.6);if (brk) {pages.push(cur);@@ -341,22 +458,23 @@ function paginate(words: Word[], maxWords: number, maxChars: number): Word[][] {chars = 0;}cur.push(w);- chars += w.text.length + 1;+ chars += w.text.length + sep.length;}if (cur.length) pages.push(cur);return pages;}-function layout(heard: Word[], style: CaptionStyle, width: number, height: number, size: CaptionSize, letters: CaptionLetters, lead: number): { pages: Word[][]; states: State[] } {+function layout(heard: Word[], style: CaptionStyle, width: number, height: number, size: CaptionSize, letters: CaptionLetters, lead: number, lang: string): { pages: Word[][]; states: State[] } {const words = heard.map((w) => ({ ...w, start: Math.max(0, w.start - lead), end: Math.max(0, w.end - lead) }));const s = CAPTION_STYLES[style];const u = (Math.min(width, height) / 100) * scaleOf(size);// Capitals are wider than small letters, so fewer of them fit on a line.- const wide = CHAR_EM[style] * (letters === "capitals" && style !== "bold" ? 1.2 : letters !== "capitals" && style === "bold" ? 0.85 : 1);+ const wide = FULL_WIDTH.has(lang) ? 1 : CHAR_EM[style] * (letters === "capitals" && style !== "bold" ? 1.2 : letters !== "capitals" && style === "bold" ? 0.85 : 1);const perLine = Math.max(8, Math.floor(boxWidth(style, width, height) / (FONT[style] * u * wide)));- const pages = paginate(words, s.maxWords, perLine * 2);+ // Words written without spaces are short (は, を, 的), so a caption holds more of them.+ const pages = paginate(words, s.maxWords * (UNSPACED.has(lang) ? 3 : 1), perLine * 2, joiner(lang));// Capitals and lowercase read better without commas and full stops; question and exclamation marks stay.- const shown = (t: string) => (letters === "as_said" ? t : t.replace(/[.,;:]+$/, ""));+ const shown = (t: string) => (letters === "as_said" ? t : t.replace(/[.,;:。、,;:،؛]+$/, ""));const states: State[] = [];let clock = 0;const push = (st: State) => {@@ -400,7 +518,7 @@ function textOn(hex: string): string {return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.6 ? "#111111" : "#FFFFFF";}-function pageHtml(style: CaptionStyle, o: { width: number; height: number; position: CaptionPosition; size: CaptionSize; color: string; letters: CaptionLetters; background?: string }): string {+function pageHtml(style: CaptionStyle, o: { width: number; height: number; position: CaptionPosition; size: CaptionSize; color: string; letters: CaptionLetters; lang: string; background?: string }): string {const { width: W, height: H } = o;const vertical = H > W;const font = FONT[style] * (Math.min(W, H) / 100) * scaleOf(o.size);@@ -424,18 +542,21 @@ function pageHtml(style: CaptionStyle, o: { width: number; height: number; positclean: `.cap{font:700 ${font}px/1.25 ${sans};color:#fff;text-shadow:0 .04em .12em rgba(0,0,0,.9),0 0 .35em rgba(0,0,0,.55)}`,boxed: `.cap{font:700 ${font}px/1.55 ${sans};color:#fff}.inner{display:inline;background:rgba(0,0,0,.74);padding:.12em .45em;border-radius:.28em;-webkit-box-decoration-break:clone;box-decoration-break:clone}`,}[style];- return `<!doctype html><html><head><meta charset="utf-8"><style>+ // The language tag makes capitals right for the language (Turkish i -> İ, not I); right-to-left scripts read that way.+ const lang = /^[a-z]{2,3}$/.test(o.lang) ? o.lang : "en";+ return `<!doctype html><html lang="${lang}"${RTL.has(lang) ? ' dir="rtl"' : ""}><head><meta charset="utf-8"><style>html,body{margin:0;width:${W}px;height:${H}px;overflow:hidden;background:${o.background ? `#000 url(${o.background}) center/100% 100% no-repeat` : "transparent"}}.cap{position:absolute;left:50%;width:${boxWidth(style, W, H)}px;text-align:center;text-wrap:balance;--hl:${o.color};--on:${textOn(o.color)};${place};-webkit-font-smoothing:antialiased}.inner{display:block;transform-origin:50% 60%}${css}.cap{text-transform:${{ as_said: "none", capitals: "uppercase", lowercase: "lowercase" }[o.letters]}}+${UNSPACED.has(lang) ? ".w{margin-left:.03em;margin-right:.03em}" + (style === "highlight" ? ".w{margin-left:-.07em;margin-right:-.07em}" : "") : ""}</style></head><body><div class="cap"><div class="inner" id="inner"></div></div><script>const esc = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);window.paint = (s) => {const el = document.getElementById("inner");el.style.transform = s.scale === 1 ? "" : "scale(" + s.scale + ")";- el.innerHTML = s.words.map((w, i) => '<span class="w' + (i === s.active ? " on" : "") + (${style === "reveal"} && i > s.active ? " later" : "") + '" data-t="' + esc(w) + '">' + esc(w) + "</span>").join(" ");+ el.innerHTML = s.words.map((w, i) => '<span class="w' + (i === s.active ? " on" : "") + (${style === "reveal"} && i > s.active ? " later" : "") + '" data-t="' + esc(w) + '">' + esc(w) + "</span>").join(${JSON.stringify(joiner(lang))});};</script></body></html>`;}@@ -486,14 +607,15 @@ async function timedWords(video: string, o: CaptionOptions): Promise<{ transcripconst transcript = await transcribe(video, o.language ?? "auto");const edited = o.text?.trim();const same = edited !== undefined && norm(edited.replace(/\s+/g, "")) === norm(transcript.text.replace(/\s+/g, "")) && !edited.includes("\n");- return { transcript, words: edited && !same ? alignText(transcript.words, edited) : transcript.words };+ return { transcript, words: edited && !same ? alignText(transcript.words, edited, transcript.language) : transcript.words };}// One still of the real video with the real captions on it, so the panel shows exactly what will be made.export async function previewCaptions(video: string, o: CaptionOptions): Promise<{ image: string; at: number }> {const info = await probe(video);- const { words } = await timedWords(video, o);- const { pages, states } = layout(words, o.style, info.width, info.height, o.size, lettersOf(o), o.lead ?? LEAD);+ const { transcript, words } = await timedWords(video, o);+ const lang = transcript.language;+ const { pages, states } = layout(words, o.style, info.width, info.height, o.size, lettersOf(o), o.lead ?? LEAD, lang);// A caption of a few words, about a third of the way in, mid-sentence.const want = (pages[0]?.[0].start ?? 0) + ((pages.at(-1)?.at(-1)?.end ?? 0) - (pages[0]?.[0].start ?? 0)) * 0.33;const page = pages.filter((p) => p.length >= Math.min(2, CAPTION_STYLES[o.style].maxWords)).sort((p, q) => Math.abs(p[0].start - want) - Math.abs(q[0].start - want))[0] ?? pages[0];@@ -507,7 +629,7 @@ export async function previewCaptions(video: string, o: CaptionOptions): Promiseawait run(FFMPEG, ["-v", "error", "-y", "-ss", at.toFixed(3), "-i", video, "-frames:v", "1", "-q:v", "3", frame], BIG);const background = `data:image/jpeg;base64,${readFileSync(frame).toString("base64")}`;const image = join(CACHE_DIR, `preview-${key}.jpg`);- await withPage(info.width, info.height, pageHtml(o.style, { ...info, position: o.position, size: o.size, color: pickColor(o), letters: lettersOf(o), background }), async (p) => {+ await withPage(info.width, info.height, pageHtml(o.style, { ...info, position: o.position, size: o.size, color: pickColor(o), letters: lettersOf(o), lang, background }), async (p) => {if (state) await p.evaluate((s) => (window as unknown as { paint: (s: unknown) => void }).paint(s), state);await p.screenshot({ path: image, type: "jpeg", quality: 85 });});@@ -528,20 +650,23 @@ export interface CaptionResult {words: number;duration: number;transcript: string;+ language: string;model: string;}export async function burnCaptions(video: string, o: CaptionOptions, output: string): Promise<CaptionResult> {const info = await probe(video);const { transcript, words } = await timedWords(video, o);- const { pages, states } = layout(words, o.style, info.width, info.height, o.size, lettersOf(o), o.lead ?? LEAD);+ const lang = transcript.language;+ const sep = joiner(lang);+ const { pages, states } = layout(words, o.style, info.width, info.height, o.size, lettersOf(o), o.lead ?? LEAD, lang);if (!states.length) throw new Error("There are no words to put on screen.");const work = mkdtempSync(join(tmpdir(), "flow-captions-"));try {// Draw every distinct caption once, as a transparent picture the size of the video.const files = new Map<string, string>();- await withPage(info.width, info.height, pageHtml(o.style, { ...info, position: o.position, size: o.size, color: pickColor(o), letters: lettersOf(o) }), async (p) => {+ await withPage(info.width, info.height, pageHtml(o.style, { ...info, position: o.position, size: o.size, color: pickColor(o), letters: lettersOf(o), lang }), async (p) => {await p.screenshot({ path: join(work, "blank.png"), omitBackground: true });for (const s of states) {const id = JSON.stringify([s.words, s.active, s.scale]);@@ -592,11 +717,11 @@ export async function burnCaptions(video: string, o: CaptionOptions, output: str.map((p, i) => {const next = pages[i + 1]?.[0].start;const end = next !== undefined ? Math.min(p[p.length - 1].end + 0.25, next) : p[p.length - 1].end + 0.25;- return `${i + 1}\n${stamp(p[0].start)} --> ${stamp(end)}\n${p.map((w) => w.text).join(" ")}\n`;+ return `${i + 1}\n${stamp(p[0].start)} --> ${stamp(end)}\n${p.map((w) => w.text).join(sep)}\n`;}).join("\n"),);- return { output, srt, captions: pages.length, words: words.length, duration: info.duration, transcript: words.map((w) => w.text).join(" "), model: transcript.model };+ return { output, srt, captions: pages.length, words: words.length, duration: info.duration, transcript: words.map((w) => w.text).join(sep), language: lang, model: transcript.model };} finally {rmSync(work, { recursive: true, force: true });}diff --git a/src/core.ts b/src/core.tsindex 4e95c2c..99e2489 100644--- a/src/core.ts+++ b/src/core.ts@@ -79,7 +79,12 @@ const captionFields = {.optional().describe("as_said keeps normal capitals (sentence starts, names); capitals is the high-energy short-form look; lowercase is the calm, casual look. Default: capitals for bold, as_said for the rest."),text: z.string().max(50_000).optional().describe("Corrected words, to fix anything misheard. Timings are kept for every word that still matches; a line break starts a new caption."),- language: z.string().default("auto").describe("Spoken language code (en, es, de...) or auto."),+ language: z+ .string()+ .default("auto")+ .describe(+ "Spoken language as a code: en, es, fr, de, pt, tr, ja, zh, ar... Pass it whenever you know it. auto detects it (a 60 MB detector downloads once). English uses a 148 MB model; every other language a 574 MB one, each downloaded the first time.",+ ),};export const shapes = {@@ -132,7 +137,7 @@ export const shapes = {},transcribe: {video: z.string().min(1).describe("Absolute path of a video or audio file on this computer."),- language: z.string().default("auto"),+ language: z.string().default("auto").describe("Spoken language code (en, es, tr, ja...) or auto. Pass it whenever you know it."),words: z.boolean().default(true).describe("Include every word with its start and end time in seconds."),},caption_preview: captionFields,diff --git a/src/index.ts b/src/index.tsindex b1fce36..57fc37a 100644--- a/src/index.ts+++ b/src/index.ts@@ -300,7 +300,7 @@ server.registerTool({title: "Hear the words in a video or audio file",description:- "Transcribe a video or audio file on this computer with every word's start and end time (whisper.cpp, local and free; the first call downloads a 148 MB speech model once). Use the times to check a take said the right words and to cut lines out of it for flow_assemble's voice_lines.",+ "Transcribe a video or audio file on this computer with every word's start and end time (whisper.cpp, local and free, about 100 languages; pass `language` when you know it. The first call in English downloads a 148 MB speech model once, in any other language a 574 MB one). Use the times to check a take said the right words and to cut lines out of it for flow_assemble's voice_lines.",inputSchema: shapes.transcribe,annotations: { readOnlyHint: true, openWorldHint: false },},@@ -312,7 +312,7 @@ server.registerTool({title: "Add captions to a video",description:- "Burn spoken-word captions into a video, in the style short-form apps use, for landscape or vertical footage (local and free: whisper.cpp hears the words on this computer, nothing is uploaded). Styles: bold (big capitals, the spoken word lights up), highlight, reveal, clean, boxed. The first call on a computer downloads a 148 MB speech model once. Saves <name>-captions.mp4 plus an .srt, and returns the transcript: if a word was misheard, call again with the corrected `text` - matching words keep their timing.",+ "Burn spoken-word captions into a video, in the style short-form apps use, for landscape or vertical footage (local and free: whisper.cpp hears the words on this computer, nothing is uploaded). Styles: bold (big capitals, the spoken word lights up), highlight, reveal, clean, boxed. Works in about 100 languages, including ones written without spaces (Japanese, Chinese, Thai) and right to left (Arabic, Hebrew); pass `language` (en, es, tr, ja...) whenever you know it. The first call downloads a speech model once: 148 MB for English, 574 MB for other languages. Saves <name>-captions.mp4 plus an .srt, and returns the transcript: if a word was misheard, call again with the corrected `text` - matching words keep their timing.",inputSchema: shapes.captions,annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },},diff --git a/src/playbook.ts b/src/playbook.tsindex ed8ca8d..0394488 100644--- a/src/playbook.ts+++ b/src/playbook.ts@@ -5,7 +5,7 @@ export const PLAYBOOK = {"Plan the whole piece as scenes of one shot each, then send them in ONE flow_generate call so file numbering and chaining work.","Tell the user the expected credit total before queueing anything that costs credits.","Call flow_wait repeatedly until finished is true; scenes run one at a time with 25-70 s pauses.",- "To put the spoken words on screen, call flow_captions on the finished film (style bold for short-form, clean for subtitles). Read the transcript it returns; if a word is misheard, call again with the corrected text.",+ "To put the spoken words on screen, call flow_captions on the finished film (style bold for short-form, clean for subtitles), with `language` set to the language spoken. Read the transcript it returns; if a word is misheard, call again with the corrected text.","If an image batch finishes with \"still failed: scene ...\" in its note, call flow_retry with its job id: only those images are made again, under their own scene numbers.","No call blocks for more than about 45 s. A reply with still_working and a task_id means Flow is still busy with it: pass the task_id to flow_wait, and never repeat the call.",],diff --git a/studio/index.html b/studio/index.htmlindex b0a49a5..eef10e7 100644--- a/studio/index.html+++ b/studio/index.html@@ -369,6 +369,8 @@ audio{width:100%;margin-top:8px;filter:invert(1) hue-rotate(180deg)}<button type="button" class="btn small ghost" id="cap_film">From my films</button></div><div class="rowbtns" style="flex-wrap:nowrap"><input type="text" id="cap_path" spellcheck="false" placeholder="…or paste where a video is saved" style="flex:1;min-width:0"><button type="button" class="btn small" id="cap_pathgo">Use</button></div>+ <label class="f" for="cap_lang">Spoken language</label>+ <select id="cap_lang"></select><label class="f">Style</label><div class="capstyles" id="cap_styles"></div><div class="grid2">@@ -848,8 +850,30 @@ const capLetters = (style) => S.captions.letters?.[style] ?? (style === "bold" ?const CASE_CSS = { as_said: "none", capitals: "uppercase", lowercase: "lowercase" };// Size is a percentage of the style's normal size; older saved settings said small, medium or large.const capSize = () => (typeof S.captions.size === "number" ? S.captions.size : { small: 80, medium: 100, large: 120 }[S.captions.size] ?? 100);+// The language spoken in the video. The first time it is the browser's own language when it is one we list, else English.+const capLang = () => S.captions.language ?? "en";+const capLangName = (code) => capSetup?.languages?.find((l) => l.code === code)?.name ?? code;+function capDefaultLang() {+ const mine = (navigator.language || "en").toLowerCase().split("-")[0];+ const code = { nb: "no", nn: "no", fil: "tl", iw: "he" }[mine] ?? mine;+ return capSetup?.languages?.some((l) => l.code === code) ? code : "en";+}+function renderCapLangs() {+ if (!capSetup?.languages) return;+ $("#cap_lang").innerHTML = `<option value="auto">Detect automatically</option>` + capSetup.languages.map((l) => `<option value="${l.code}">${esc(l.name)}</option>`).join("");+ $("#cap_lang").value = capLang();+}+// What has to download before this language can be heard, said in words; "" when nothing does.+function capFetchNote() {+ const m = capSetup?.models, mb = capSetup?.download_mb, l = capLang();+ if (!m) return "";+ if (l === "en") return m.english ? "" : `Getting the speech model for English (${mb.english} MB, one time only), then listening to the video…`;+ if (l === "auto" && !m.detect) return `Getting a small model that recognises the language (${mb.detect} MB, one time only), then listening to the video…`;+ if (l === "auto") return m.english && m.other ? "" : `Listening to the video… The first time a language turns up, its speech model downloads first, one time only (${mb.english} MB for English, ${mb.other} MB for any other language).`;+ return m.other ? "" : `Getting the speech model for ${capLangName(l)} (${mb.other} MB, one time only; a few minutes on a slow connection), then listening to the video…`;+}function capOpts() {- const c = S.captions, o = { video: c.video.path, style: c.style, position: c.position, size: capSize() };+ const c = S.captions, o = { video: c.video.path, style: c.style, position: c.position, size: capSize(), language: capLang() };if (CAP_COLORS[c.style]) o.color = capColor(c.style);o.letters = capLetters(c.style);const t = $("#cap_text").value;@@ -883,6 +907,8 @@ async function capReady() {if (capSetup?.ready) return true;try { capSetup = await api("caption_setup"); } catch (err) { toast(err.message, true); return false; }const s = capSetup;+ if (!S.captions.language) { S.captions.language = capDefaultLang(); save(); }+ renderCapLangs();$("#cap_setup").innerHTML = s.ready ? "" : `<div class="hint" style="margin:0 0 18px"><b>One-time setup.</b> To hear the words, captions need whisper.cpp, a free program, on ${PLACE.computer}: ${esc(s.whisper_hint)}<div class="rowbtns" style="margin-top:10px"><button class="btn small ghost" id="cap_recheck" type="button">I've installed it, check again</button></div></div>`;return s.ready;@@ -895,15 +921,15 @@ async function setCapVideo(v) {async function capListen() {const c = S.captions;if (!c.video || !guard() || !(await capReady())) return;- // The very first time, the speech model downloads before anything can be heard.- showPreview(null, capSetup?.model ? "Listening to the video…" : "Getting the speech model (148 MB, one time only), then listening to the video…");+ // The first time in a language, its speech model downloads before anything can be heard.+ showPreview(null, capFetchNote() || "Listening to the video…");$("#cap_textNote").textContent = "";try {- const out = await api("transcribe", { video: c.video.path });- if (capSetup) capSetup.model = out.model;+ const out = await api("transcribe", { video: c.video.path, language: capLang(), words: false });+ api("caption_setup").then((s) => { capSetup = s; }, () => {});capHeard = out.text; capFor = c.video.path;$("#cap_text").value = c.text || out.text;- $("#cap_textNote").textContent = `· ${out.words} words heard`;+ $("#cap_textNote").textContent = `· ${out.word_count} words heard${capLang() === "auto" ? ` in ${capLangName(out.language)}` : ""}`;await capPreview();} catch (err) { showPreview(null, err.message, true); }}@@ -922,6 +948,12 @@ function capPreviewSoon(ms = 350) { clearTimeout(capTimer); capTimer = setTimeou$("#cap_styles").addEventListener("click", (e) => { const b = e.target.closest("[data-capstyle]"); if (!b) return; S.captions.style = b.dataset.capstyle; save(); renderCaptions(); capPreviewSoon(); });$("#cap_colors").addEventListener("click", (e) => { const b = e.target.closest("[data-capcolor]"); if (!b) return; (S.captions.colors ??= {})[S.captions.style] = b.dataset.capcolor; save(); renderCaptions(); capPreviewSoon(); });$("#cap_video").addEventListener("click", (e) => { if (!e.target.closest("#cap_clear")) return; S.captions.video = null; S.captions.text = ""; save(); capHeard = ""; capFor = ""; $("#cap_text").value = ""; $("#cap_textNote").textContent = ""; showPreview(null); renderCaptions(); });+$("#cap_lang").addEventListener("change", (e) => {+ // Corrections were made against the words heard in the old language, so they go too.+ S.captions.language = e.target.value; S.captions.text = ""; save();+ capHeard = ""; capFor = ""; $("#cap_text").value = ""; $("#cap_out").innerHTML = "";+ capListen();+});$("#cap_up").onclick = () => { pickTarget = { kind: "capvideo", i: 0 }; $("#file").accept = "video/*"; $("#file").click(); };$("#cap_film").onclick = () => openFilms("captions");$("#cap_pathgo").onclick = () => { const p = $("#cap_path").value.trim().replace(/^["']|["']$/g, ""); if (!p) return; $("#cap_path").value = ""; setCapVideo({ path: p, name: p.split(/[\\/]/).pop() }); };