From ded94ae424fbaa56e21e9531a8c9e54a5d0f07eb Mon Sep 17 00:00:00 2001 From: GodsQuantum <193283917+GodsQuantum@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:32:38 +0100 Subject: [PATCH] feat(asr): prefer Parakeet Ultra with strict acoustic word timings --- README.fr.md | 2 +- README.md | 4 +- frontend/src/lib/speaches-discovery.js | 5 +- frontend/src/lib/views/SettingsView.svelte | 8 +- frontend/tests/speaches-discovery.test.mjs | 12 ++- src/api/speaches.rs | 11 ++- src/domain.rs | 2 +- src/jobs.rs | 90 +++++++++++++++++++++- src/media/transcribe.rs | 38 +++++---- tools/standup_corpus.py | 35 +++++---- 10 files changed, 165 insertions(+), 42 deletions(-) diff --git a/README.fr.md b/README.fr.md index 4075d14..a4b2921 100644 --- a/README.fr.md +++ b/README.fr.md @@ -22,7 +22,7 @@ --- -AutoSubs s'occupe de ce qui arrive **une fois la vidéo prête** : récupérer les timings mot-à-mot depuis Whisper/Speaches ou un fichier de sous-titres existant, corriger le texte, réparer les timings, appliquer un style, prévisualiser le bon format et laisser FFmpeg/libass incruster le résultat. Pour les traitements récurrents, un Workflow surveille un dossier et exécute le même pipeline automatiquement. +AutoSubs s'occupe de ce qui arrive **une fois la vidéo prête** : récupérer les timings acoustiques mot-à-mot depuis Speaches/Parakeet Ultra (par défaut), ou Whisper ou un fichier de sous-titres existant, corriger le texte, réparer les timings, appliquer un style, prévisualiser le bon format et laisser FFmpeg/libass incruster le résultat. Pour les traitements récurrents, un Workflow surveille un dossier et exécute le même pipeline automatiquement. Le navigateur n'est pas le moteur métier. Rust possède la normalisation des timings, le découpage des lignes, la persistance, le rendu et l'état des workflows. L'UI appelle cette API : un traitement manuel et un traitement automatique passent donc par les mêmes règles. diff --git a/README.md b/README.md index 1de5d1a..b9b06f7 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ --- -AutoSubs is for the part that happens **after you have a video**: get word timings from Whisper/Speaches or import an existing subtitle file, clean up the text, repair bad timing, style it once, preview the right canvas, and let FFmpeg burn it with libass. For recurring work, a Workflow watches a folder and runs the same pipeline automatically. +AutoSubs is for the part that happens **after you have a video**: get acoustically aligned word timings from Speaches Parakeet Ultra (default), or from Whisper or import an existing subtitle file, clean up the text, repair bad timing, style it once, preview the right canvas, and let FFmpeg burn it with libass. For recurring work, a Workflow watches a folder and runs the same pipeline automatically. It is deliberately not a browser-only subtitle toy. The Rust backend owns timing normalization, segmentation, persistence, rendering and workflow state. The web UI is a client of that API, so manual jobs and automated jobs go through the same rules. @@ -315,7 +315,7 @@ In the Editor, scrub through the video preview and mark **Start here** and **End ### Cloud9 stand-up transcript/search utility -A local optional Python 3 utility under `tools/standup_corpus.py` inventories the stand-up media folder on Cloud9, chunks audio for the existing Speaches/WhisperX alignment services, saves same-stem Markdown/SRT/word-timestamp JSON sidecars, and updates an SQLite FTS5 search index with absolute video timestamps. The corpus utility is optional and Cloud9-specific; it is **not** enabled for general Docker or AppImage installs. See `tools/STANDUP_CORPUS_CLOUD9.md` for service setup, status, query examples, and original-media safeguards. +A local optional Python 3 utility under `tools/standup_corpus.py` inventories the stand-up media folder on Cloud9, chunks audio for the existing Speaches Parakeet Ultra native word-timing API (without a separate aligner), saves same-stem Markdown/SRT/word-timestamp JSON sidecars, and updates an SQLite FTS5 search index with absolute video timestamps. The corpus utility is optional and Cloud9-specific; it is **not** enabled for general Docker or AppImage installs. See `tools/STANDUP_CORPUS_CLOUD9.md` for service setup, status, query examples, and original-media safeguards. ## Development diff --git a/frontend/src/lib/speaches-discovery.js b/frontend/src/lib/speaches-discovery.js index 1a56804..b03595c 100644 --- a/frontend/src/lib/speaches-discovery.js +++ b/frontend/src/lib/speaches-discovery.js @@ -1,4 +1,5 @@ const MODEL_PREFS = [ + 'handy-computer/parakeet-ultra-gguf', 'deepdml/faster-whisper-large-v3-turbo-ct2', 'Systran/faster-whisper-large-v3', ]; @@ -43,14 +44,14 @@ export async function probeSpeaches(value, fetcher = fetch) { if (!health || !Array.isArray(models?.data)) throw new Error('Invalid Cloud9-Speaches API response'); const ids = /** @type {{id?:string}[]} */ (models.data).map(x => x?.id).filter(x => typeof x === 'string'); const model = MODEL_PREFS.find(x => ids.includes(x)); - if (!model) throw new Error('No supported Whisper Turbo model is installed'); + if (!model) throw new Error('No supported word-timestamp ASR model is installed'); return { origin, transcriptionUrl: origin + '/v1/audio/transcriptions', alignmentUrl: '', model, alignmentModel: '', - backend: 'whisper-native-words', + backend: model.includes('parakeet-ultra') ? 'parakeet-ultra-ctc-words' : 'whisper-native-words', backendVerified: false, }; } diff --git a/frontend/src/lib/views/SettingsView.svelte b/frontend/src/lib/views/SettingsView.svelte index 939e19c..4a86f0d 100644 --- a/frontend/src/lib/views/SettingsView.svelte +++ b/frontend/src/lib/views/SettingsView.svelte @@ -21,7 +21,11 @@ const next: SettingsView = { ...previous, localTranscriptionEnabled: true, localFallbackEnabled: false, localTranscriptionUrl: found.transcriptionUrl, - localTranscriptionModel: found.model + localTranscriptionModel: found.model, + // Strict native CTC requires an explicit language; preserve existing selection. + language: found.model.includes('parakeet-ultra') + ? (previous.language.trim() || 'fr') + : previous.language }; // Preserve all secret keys and the existing primary/OmniRoute provider. await api.saveSettings(next); @@ -68,7 +72,7 @@
{#if speachesPrevious}{/if}
-

Uses Whisper Turbo native word timing, without any separate aligner; missing timestamps are rejected. For a Docker deployment on another machine, enter its reachable private-LAN HTTPS/HTTP address.

+

Prefers Parakeet Ultra with native acoustic word alignment in Speaches. Missing or inferred word timestamps are rejected. Explicit language is required (French by default). For a Docker deployment on another machine, enter its reachable private-LAN HTTPS/HTTP address.

{$dictionary.primaryProvider}
diff --git a/frontend/tests/speaches-discovery.test.mjs b/frontend/tests/speaches-discovery.test.mjs index fdeb2dc..1fb2318 100644 --- a/frontend/tests/speaches-discovery.test.mjs +++ b/frontend/tests/speaches-discovery.test.mjs @@ -30,9 +30,19 @@ test('discovers native word-timestamp Whisper Turbo without forced aligner', asy assert.equal(calls.length,2); }); +test('prioritizes Parakeet Ultra when both supported ASR models are present', async () => { + const fake = async (url) => ({ok:true,json:async()=>url.endsWith('/v1/models') + ? {data:[{id:'deepdml/faster-whisper-large-v3-turbo-ct2'},{id:'handy-computer/parakeet-ultra-gguf'}]} + : {message:'OK'}}); + const result = await probeSpeaches('http://127.0.0.1:8005',fake); + assert.equal(result.model,'handy-computer/parakeet-ultra-gguf'); + assert.equal(result.backend,'parakeet-ultra-ctc-words'); + assert.equal(result.backendVerified,false); +}); + test('rejects missing Whisper model before changing settings', async () => { const fake = async (url) => ({ok:true,json:async()=>url.endsWith('/v1/models')?{data:[]}:{message:'OK'}}); - await assert.rejects(() => probeSpeaches('http://127.0.0.1:8005',fake),/Whisper Turbo/); + await assert.rejects(() => probeSpeaches('http://127.0.0.1:8005',fake),/word-timestamp ASR model/); }); test('one-click connection performs same-origin authenticated-app-server probe only', async () => { diff --git a/src/api/speaches.rs b/src/api/speaches.rs index 07769b7..bfabda6 100644 --- a/src/api/speaches.rs +++ b/src/api/speaches.rs @@ -12,6 +12,7 @@ use std::{ }; const MODEL_PREFS: &[&str] = &[ + "handy-computer/parakeet-ultra-gguf", "deepdml/faster-whisper-large-v3-turbo-ct2", "Systran/faster-whisper-large-v3", ]; @@ -175,14 +176,20 @@ pub async fn probe(Json(request): Json) -> AppResult() + }; + let timed_text: String = native + .iter() + .filter_map(|word| word.word.as_deref()) + .collect::>() + .join(" "); + if letters(text) != letters(&timed_text) { + bail!("ASR native word timestamps omit or alter recognized text"); + } + } let mut grouped = Vec::::with_capacity(native.len()); let mut pending = Vec::::new(); let mut pending_at = None::; @@ -2224,6 +2244,64 @@ mod tests { assert_eq!(timeline.words[6].word, "vexés"); } + #[test] + fn reject_native_word_timestamps_when_recognized_word_is_missing() { + let input = TranscriptionResponse { + text: Some("bonjour les amis".into()), + words: Some(vec![ + RawWord { + word: Some("bonjour".into()), + start: Some(0.1), + end: Some(0.45), + }, + RawWord { + word: Some("amis".into()), + start: Some(0.55), + end: Some(0.85), + }, + ]), + segments: None, + }; + assert!( + validated_native_word_timeline(&input, 1.0) + .unwrap_err() + .to_string() + .contains("omit or alter") + ); + } + + #[test] + fn accept_native_word_timings_when_whitespace_tokens_differ_but_lexemes_match() { + let input = TranscriptionResponse { + text: Some("aujourd'hui est magnifique".into()), + words: Some(vec![ + RawWord { + word: Some("aujourd'".into()), + start: Some(0.1), + end: Some(0.35), + }, + RawWord { + word: Some("hui".into()), + start: Some(0.35), + end: Some(0.55), + }, + RawWord { + word: Some("est".into()), + start: Some(0.55), + end: Some(0.7), + }, + RawWord { + word: Some("magnifique".into()), + start: Some(0.7), + end: Some(1.2), + }, + ]), + segments: None, + }; + let line = validated_native_word_timeline(&input, 1.3).unwrap(); + assert_eq!(line.timing_quality, TimingQuality::Exact); + } + #[test] fn coalesce_zero_span_whisper_clitics_without_inventing_times_or_words() { let src = TranscriptionResponse { @@ -2292,6 +2370,16 @@ mod tests { end: Some(1.55 + idx as f64 * 0.10), }); } + // The text-only reference must include every timed lexical word. + // The previous fixture appended 120 word spans without transcript text. + let filler = (0..120) + .map(|idx| format!("suite{idx}")) + .collect::>() + .join(" "); + realistic.text = Some(format!( + "{} {filler}", + src.text.as_deref().unwrap_or_default() + )); let timeline = validated_native_word_timeline(&realistic, 14.0).unwrap(); assert_eq!(timeline.timing_quality, TimingQuality::Inferred); assert_eq!(timeline.words[0].word, "C'est"); diff --git a/src/media/transcribe.rs b/src/media/transcribe.rs index e90cff2..368806b 100644 --- a/src/media/transcribe.rs +++ b/src/media/transcribe.rs @@ -63,9 +63,13 @@ pub(crate) fn models_endpoint(url: &str) -> String { } // Capability-gated requests, not a hardwired option for every model. -fn supports_whisper_word_timestamps(model: &str) -> bool { +fn supports_native_word_timestamps(model: &str) -> bool { let model = model.trim().to_ascii_lowercase(); - model.contains("whisper") || model.ends_with("-ct2") || model.contains("/ct2") + model.contains("whisper") + || model.ends_with("-ct2") + || model.contains("/ct2") + || model.ends_with("/parakeet-ultra-gguf") + || model == "parakeet-ultra-gguf" } async fn request_endpoint( @@ -88,22 +92,22 @@ async fn request_endpoint( .file_name("audio.wav") .mime_str("audio/wav") .map_err(TranscriptionError::Http)?; - // Whisper/CT2 implement the OpenAI verbose_json word timestamp extension. - // Other OpenAI-compatible ASR engines (notably Qwen3-ASR GGUF) may reject - // timestamp_granularities with 422/503 even when plain JSON is supported. + // Whisper/CT2 and Speaches Parakeet Ultra (strict native CTC) support the + // OpenAI verbose_json word timestamp extension. Other ASR engines, such as + // Qwen3-ASR and Parakeet TDT, may reject timestamp_granularities. // Parse any native words they return, but NEVER synthesize or silently // assert native timings if the response is only text. The AutoSubs job // gate can invoke its optional one-shot aligner or fail closed. - let wants_whisper_words = supports_whisper_word_timestamps(model); + let wants_native_words = supports_native_word_timestamps(model); let mut form = multipart::Form::new().part("file", part).text( "response_format", - if wants_whisper_words { + if wants_native_words { "verbose_json" } else { "json" }, ); - if wants_whisper_words { + if wants_native_words { form = form.text("timestamp_granularities[]", "word"); } if !model.trim().is_empty() { @@ -270,18 +274,24 @@ mod endpoint_regression_tests { #[test] fn request_word_timestamp_capability_is_model_aware() { - assert!(supports_whisper_word_timestamps( + assert!(supports_native_word_timestamps( "deepdml/faster-whisper-large-v3-turbo-ct2" )); - assert!(supports_whisper_word_timestamps("whisper-large-v3-turbo")); - assert!(supports_whisper_word_timestamps("whisper-1")); - assert!(!supports_whisper_word_timestamps( + assert!(supports_native_word_timestamps("whisper-large-v3-turbo")); + assert!(supports_native_word_timestamps("whisper-1")); + assert!(supports_native_word_timestamps( + "handy-computer/parakeet-ultra-gguf" + )); + assert!(supports_native_word_timestamps( + "other-provider/parakeet-ultra-gguf" + )); + assert!(!supports_native_word_timestamps( "handy-computer/Qwen3-ASR-1.7B-gguf" )); - assert!(!supports_whisper_word_timestamps( + assert!(!supports_native_word_timestamps( "nvidia/parakeet-tdt-0.6b-v3" )); - assert!(!supports_whisper_word_timestamps("gpt-transcribe")); + assert!(!supports_native_word_timestamps("gpt-transcribe")); } #[tokio::test] diff --git a/tools/standup_corpus.py b/tools/standup_corpus.py index 642dade..ad47d64 100644 --- a/tools/standup_corpus.py +++ b/tools/standup_corpus.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """Cloud9 stand-up corpus: lossless source preservation, aligned word sidecars, searchable index. -Uses the existing AutoSubs Docker FFmpeg and Cloud9-Speaches/WhisperX. Python stdlib only. +Uses the existing AutoSubs Docker FFmpeg and Cloud9-Speaches Parakeet Ultra native word alignment. Python stdlib only. """ import argparse import datetime as dt @@ -25,9 +25,8 @@ TMP_CONTAINER = os.environ.get("AUTOSUBS_CORPUS_TMP_CONTAINER", "/data/work/standup_corpus") CONTAINER_SOURCE = os.environ.get("AUTOSUBS_CORPUS_CONTAINER_ROOT", "/data/production-active").rstrip("/") STT = os.environ.get("AUTOSUBS_CORPUS_STT_URL", "http://127.0.0.1:8005/v1/audio/transcriptions") -ALIGN = os.environ.get("AUTOSUBS_CORPUS_ALIGN_URL", "http://127.0.0.1:8006/align") VAD = os.environ.get("AUTOSUBS_CORPUS_VAD_URL", "http://127.0.0.1:8005/v1/audio/speech/timestamps") -MODEL = os.environ.get("AUTOSUBS_CORPUS_ASR_MODEL", "deepdml/faster-whisper-large-v3-turbo-ct2") +MODEL = os.environ.get("AUTOSUBS_CORPUS_ASR_MODEL", "handy-computer/parakeet-ultra-gguf") CONTAINER_NAME = os.environ.get("AUTOSUBS_CORPUS_CONTAINER", "autosubs") LXC_ID = os.environ.get("AUTOSUBS_CORPUS_LXC_ID") EXTS = {".mp4", ".mkv", ".mov", ".m4v", ".avi", ".webm"} @@ -73,9 +72,12 @@ def multipart(fields, filename, contents, url, timeout=600): raise RuntimeError(f"{url}: HTTP {exc.code}: {exc.read(900)!r}") from exc def transcription_options(language): - # Speaches word-granularity itself calls the same remote aligner and fails 503 - # if it is briefly down. Align exactly once, explicitly, after STT. - return {"model": MODEL, "language": language, "response_format": "verbose_json"} + if not str(language).strip(): + raise ValueError("Parakeet Ultra strict word alignment requires an explicit language") + # One Speaches request gives the transcript AND acoustically grounded words. + # No secondary aligner, no interpolation and no replacement of ASR text. + return {"model": MODEL, "language": language, "response_format": "verbose_json", + "timestamp_granularities[]": "word"} def transcribe_text_or_silence(sound, language): try: @@ -128,20 +130,21 @@ def get_words(segment, start, n, language): # Silent/music-only clips can hallucinate punctuation ("... ... ..."). # Never publish punctuation-only phrases as spoken words. return [] - aligned = multipart({"transcript": raw_text, "language": language}, - "clip.wav", sound, ALIGN) - output = aligned.get("result", aligned) - rows = output.get("word_segments") or output.get("words") or [] - if not rows: raise ValueError("forced alignment returned no words") + rows = transcript.get("words") or [] + if not rows: + raise ValueError("Parakeet Ultra native CTC returned no word timestamps") + def lexemes(value): + return "".join(ch.lower() for ch in value if ch.isalnum()) + if lexemes(raw_text) != lexemes("".join(str(row.get("word") or "") for row in rows)): + raise ValueError("ASR word timestamps omit or alter transcript text") words = [] last_end = -1. for row in rows: word = str(row.get("word") or row.get("text") or "").strip() b, e = float(row["start"]), float(row["end"]) - if not word or not math.isfinite(b) or not math.isfinite(e) or b < 0 or e <= b or e > n+0.08 or b < last_end - .015: - raise ValueError(f"invalid forced alignment: {row!r}") - # Tiny overlap tolerance due to float rounding, do not invent timestamp uniformity. - b = max(b, last_end) if last_end >= 0 else b + if not word or not math.isfinite(b) or not math.isfinite(e) or b < 0 or e <= b or e > n+0.08 or b < last_end - .002: + raise ValueError(f"invalid native acoustic word timestamp: {row!r}") + # Preserve measured times, never fabricate or shift them. words.append({"word": word, "start": round(start+b, 3), "end": round(start+e, 3)}) last_end = e return words @@ -187,7 +190,7 @@ def markdown_output(video, words, duration, lang): f"- **Fichier** : `{safe_relative}`", f"- **Durée** : {timecode(duration)}", f"- **Langue** : {lang}", - f"- **Moteur** : {MODEL}; alignement WhisperX mot par mot", + f"- **Moteur** : {MODEL}; alignement acoustique natif mot par mot", "- **Horodatages** : temps absolu de la vidéo source", "- **Statut** : transcription automatique à vérifier avant publication", "", "## Transcription", ""]