From be3837ff06e9452255067cbb5ec884635a340ae2 Mon Sep 17 00:00:00 2001 From: Accusys Date: Thu, 5 Nov 2026 16:13:55 +0800 Subject: [PATCH] feat: asrx garbled text recovery - first-sentence trigger, config-driven language rotation, VLM audio rescue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - rust_asr_asrx: 3-layer recovery (auto → language rotation → VLM second reference via llama.cpp input_audio); rotation order loaded from admin_config.json asr_config block (no hard code); skips silent retry when asr_config absent (= current behavior) - output adds recovery{} block (attempts/final_result/no_intelligible_speech) - pipeline_flows: fix skip_if_exists *.asr_asrx.json -> *.asrx.json (actual output name; prevents redundant re-ASR on reprocess) - design note: docs_v1.0/DESIGN/ASRX_Garbled_Text_Language_Rotation_V1.0.md - verified on demo 004 (auto_ok, zero cost) / 020 (rotation_hit ja) / forced all-miss rotation (no_intelligible_speech via VLM refusal signal) --- config/pipeline_flows.json | 2 +- ...SRX_Garbled_Text_Language_Rotation_V1.0.md | 249 ++++++ tools/cli/rust/src/bin/rust_asr_asrx.rs | 793 +++++++++++++++--- 3 files changed, 935 insertions(+), 109 deletions(-) create mode 100644 docs_v1.0/DESIGN/ASRX_Garbled_Text_Language_Rotation_V1.0.md diff --git a/config/pipeline_flows.json b/config/pipeline_flows.json index bc9095cb..c701ceaa 100644 --- a/config/pipeline_flows.json +++ b/config/pipeline_flows.json @@ -120,7 +120,7 @@ "usage_notes": "Combines ASR and Diarization in one processor. Uses verified whisper-small-mlx model." }, "condition": { - "skip_if_exists": "*.asr_asrx.json" + "skip_if_exists": "*.asrx.json" }, "on_failure": "continue" }, diff --git a/docs_v1.0/DESIGN/ASRX_Garbled_Text_Language_Rotation_V1.0.md b/docs_v1.0/DESIGN/ASRX_Garbled_Text_Language_Rotation_V1.0.md new file mode 100644 index 00000000..d115ea1c --- /dev/null +++ b/docs_v1.0/DESIGN/ASRX_Garbled_Text_Language_Rotation_V1.0.md @@ -0,0 +1,249 @@ +# ASRX Garbled Text Recovery via Language Rotation + VLM Second Reference — V1.0 + +| 項目 | 內容 | +|------|------| +| **範圍** | ASR / ASRX 轉錄亂碼偵測與恢復機制:第一句觸發 → 語種輪詢 → VLM 第二參考 | +| **狀態** | **Draft — 待確認** | +| **適用版本** | Momentry Core V4.0+ | +| **作者** | OpenCode / Warren | +| **建立日期** | 2026-11-05 | +| **相關檔案** | `/Users/accusys/momentry_core/tools/cli/rust/src/bin/rust_asr_asrx.rs`、`/Users/accusys/momentry_core/tools/cli/rust/src/bin/rust_asrx.rs`、`/Users/accusys/momentry_core/config/pipeline_flows.json`、`/Users/accusys/momentry/config/admin_config.json` | + +--- + +## 1. 問題 + +### 1.1 現有問題 + +`rust_asr_asrx`(MLX Whisper)在語言 auto-detect 失誤時,會輸出**無意義的亂碼幻覺**,而且 +一次轉錄直接寫入 `.asr_asrx.json`,沒有任何品質檢查與恢復機制。 + +**真實案例(demo 影片 020.mp4,本機驗證)**: + +| 步驟 | 結果 | +|------|------| +| Whisper auto-detect | 偵測語言 = `nn`(Nynorsk),text = `වවවවවව…`(同一僧伽羅字符重複 100 次)| +| 生產管線產物 | `/Users/accusys/momentry/output/04be89357fb83d91ce3a0eef0579fd04.asrx.json` 即此亂碼 | +| 強制 `--language ja` 重轉 | `"ご視聴ありがとうございました"`(有意義日文)✅ | +| 強制 `--language en` | 空字串 | + +**現行程式行為**(`/Users/accusys/momentry_core/tools/cli/rust/src/bin/rust_asr_asrx.rs`): + +- `--language ` 參數存在,未指定時 auto-detect,**只跑一次** +- 轉錄結果無任何「是否為亂碼」判定 → 亂碼直接落到下游 `tkg` + +### 1.2 影響 + +| 影響 | 說明 | +|------|------| +| `tkg` 知識圖譜污染 | 亂碼字幕進入 `tkg`(依賴 asr_asrx),造成無意義時序知識 | +| 搜尋索引污染 | 亂碼進入 chunk 嵌入,降低 smart search 品質 | +| Speaker diarization 失效場景 | 亂碼 segment 仍佔用 speaker 標籤,誤導聲紋對應 | + +--- + +## 2. 實測驗證摘要(2026-11-05 smoke test) + +| 測試 | 結果 | +|------|------| +| llama.cpp `:8080`(gemma-4-12b-it + mmproj,build 11173)audio 輸入模組 | ✅ `init_audio` 啟用(官方 experimental) | +| OpenAI `input_audio` 格式(base64 wav) | ✅ HTTP 200,audio token 實際餵入(10 秒音訊 ≈ 250–285 tokens) | +| `audio_url` 格式 | ❌ 400 `unsupported content[].type` | +| 004.mp4(清晰日語)VLM 直聽 | ✅ 轉出有意義日文,與 whisper ground truth 幾乎逐字一致,3/3 穩定(temp 0.1) | +| 020.mp4(亂碼案例)VLM 直聽 | ❌ 回答「無音訊可辨」——模型判定此音訊**無可辨語音**(與 whisper 失效模式不同) | +| English prompt | 穩定(3/3 一致);日文 prompt 曾出現近空回應 | +| max_tokens | 900 以內安全(含思考模式預算) | + +**啟示**:VLM 直聽與 whisper 的失效模式互補——004 型(whisper 失效但語音清晰)VLM 可救; +020 型(BGM 重到模型判定無語音)VLM 拒答本身是**有用的負向訊號**(此段無可辨語音)。 + +--- + +## 3. 設計 + +### 3.1 決策規則總覽(已與需求方確認的定案) + +``` +Whisper auto-detect 轉錄(一次) + │ + ├─ 第一句有意義 → 直接採用,結束(零額外成本) + │ + └─ 第一句無意義(亂碼)→ 丟棄整份 auto 結果 + → 語種輪詢:← 候選序由 config 下發,預設 ja → zh → en + 每輪指定 --language 重跑,**第一個「第一句有意義」者採用即停**(短路) + │ + ├─ 某語種命中 → 採用該輪結果 → 結束 + │ + └─ 全部輪完仍無意義 → VLM 第二參考 + ├─ audio 直餵 gemma `:8080`(input_audio)→ 產生替代轉錄,有效即採用 + │ (VLM 回答「無音訊」= 負向訊號:標記為 no_intelligible_speech) + └─ 全部恢復手段都失敗 → 保留原 auto 結果 + garbled 標記(不回傳空) +``` + +**DAG 不變**:三層恢復全部封閉在 asrx stage 的 tool 內部;stage 仍為 Phase 2 平行無依賴, +`tkg` 的阻塞點(`asr_asrx` + `face_cluster`)不變。 + +### 3.2 第一句亂碼判定(garbled check) + +判定物件 = **轉錄第一個 segment 的 text**。單句測試,任一命中即判亂碼: + +| # | 指標 | 亂碼特徵 | 閾值(預設,config 可調) | +|---|------|----------|--------------------------| +| 1 | 空回應 | text 去除空白後為空 | 直接觸發輪詢 | +| 2 | 重複字符率 | top-1 字符出現次數 / 長度 | > 0.6 | +| 3 | 重複片段 | 同一 3+ 字符片段連續重複 5 次以上 | 觸發 | +| 4 | 語言置信度 | JSON 欄位 `lang_prob` < 0.4(MLX whisper 已回報) | 觸發 | +| 5 | 幻覺字符集 | text 全部由同一類 CJK/稀有字構成且長度 ≥ 20 | 觸發 | + +> 註:020 案例同時命中 #2/#3/#4/#5;004 正常案例全部通過。指標刻意保守(寧可多輪詢、 +> 不要漏判),因為輪詢成本與 whisper 轉錄本身同級,且短路設計讓命中的第一輪就停。 + +### 3.3 語種輪詢(language rotation) + +> **🔴 2026-11-05 需求方追加定案:輪詢順序全部由 `admin_config.json` 定義,程式零 hard code。** + +| 項目 | 設計 | +|------|------| + +| 項目 | 設計 | +|------|------| +| 候選序 | 預設 `["ja", "zh", "en"]`,config 下發可改 | +| 停止條件 | **短路式**:第一個「第一句有意義」的輪即採用,不求最優 | +| 重跑方式 | 同一個 MLX whisper 命令,僅加 `--language `;音訊不重擷取 | +| 成本 | 每輪與 ASR 本身同級(small 模型 10 秒音訊 < 1 秒 CPU/GPU);stage timeout 3600s 可容納 | +| 命中結果 | 該輪完整 transcript + diarization 全部採用 | + +### 3.4 VLM 第二參考(second reference) + +| 項目 | 設計 | +|------|------| +| 觸發條件 | 僅**所有語種輪完仍無意義**(成本後置,正常與可恢復案例不消耗 :8080 資源) | +| 呼叫方式 | HTTP POST `http://localhost:8080/v1/chat/completions`,content part: + `[{"type":"text","text":"<固定英文轉錄指令>"},{"type":"input_audio","input_audio":{"data":"","format":"wav"}}]` | +| 參數 | `max_tokens=500`、`temperature=0.1`(實測 3/3 穩定的組合) | +| 有效判定 | 對 VLM 回覆的 text 比照 3.2 第一句判定;通過則採用為 transcript(speaker 延用 diarization 段落切分) | +| 負向訊號 | VLM 回答「沒有音訊/無法聽」→ 標記 `no_intelligible_speech: true`(提供 tkg 過濾) | +| 音訊格式 | 16kHz mono WAV,分段後的音訊直接 base64(實測 10 秒 ≈ 160KB) | +| 失效模式 | VLM 服務不可用 / 超時 → 跳過此層,落入 3.1 最後分支(保留 auto + garbled 標記) | + +### 3.5 輸出 schema 擴充(`.asr_asrx.json`) + +```json +{ + "language": "ja", + "garbled_fallback": false, + "recovery": { + "triggered": true, + "first_sentence_check": {"meaningful": false, "reasons": ["high_repeat_char", "low_lang_prob"]}, + "attempts": [ + {"language": "auto", "result": "rejected"}, + {"language": "ja", "result": "accepted", "first_sentence": "ご視聴ありがとうございました"} + ], + "vlm_reference": { + "used": false, + "mode": "audio_direct", + "llm_url": "http://localhost:8080/v1/chat/completions", + "decision_reason": null, + "supplementary_text": null + }, + "no_intelligible_speech": false, + "final_result": "rotation_hit" + }, + "segments": [ ...(現行欄位不變)] +} +``` + +| 情境 | `final_result` | +|------|----------------| +| auto 第一句即有意義 | `auto_ok` | +| 輪詢第 N 語種命中 | `rotation_hit` | +| VLM 直聽 rescue | `vlm_rescue` | +| VLM 判定無可辨語音 | `no_intelligible_speech` | +| 全部失敗保留原結果 | `garbled_retained` | + +下游 `tkg` 可依 `recovery.final_result` / `no_intelligible_speech` 選擇性過濾該檔字幕。 + +### 3.6 Config 下發(`admin_config.json` 新增區塊) + +```json +"asr_config": { + "garbled_check_enabled": true, + "first_sentence_thresholds": { + "max_top_char_ratio": 0.6, + "min_lang_prob": 0.4, + "min_repeat_slice_repeat": 5 + }, + "language_candidates": ["ja", "zh", "en"], + "vlm_rescue_enabled": true, + "vlm_max_tokens": 500, + "vlm_temperature": 0.1, + "vlm_timeout_secs": 120 +} +``` + +**讀取機制(確保非 hard code)**: + +| 項目 | 設計 | +|------|------| +| 讀取者 | `rust_asr_asrx` 每次啟動**直接讀 `admin_config.json`**(fresh process → 每次都拿到最新值,admin API `reload` 後下一個 job 即生效,無需重啟 worker) | +| 檔案路徑 | 環境變數 `MOMENTRY_ADMIN_CONFIG` 優先;未設定時沿用與 `AdminConfigManager` 相同的預設(`config/admin_config.json` 解析邏輯) | +| 覆寫方式 | CLI `--languages "ja,zh,en"`、`--no-vlm` 僅供手動測試覆寫,**非程式主路徑** | +| 缺 config 時 | 退回編譯期預設(`ja,zh,en` + 文件所述閾值)並印 warning——僅為保底,不算 hard code 主路徑 | +| 缺 `asr_config` 區塊 | `garbled_check_enabled` 視為 `false`(關閉 = 回到現行行為),其餘用預設值 | + +| 項目 | 說明 | +|------|------| +| `garbled_check_enabled` | **總開關;false 時行為回到現行(純 auto,零改動風險)** | +| `language_candidates` | 語種輪詢候選序 | +| `vlm_rescue_enabled` | 第三層獨立開關(會佔用 :8080 資源) | + +### 3.7 適用工具與後續推廣 + +| 工具 | 本版本 | 後續 | +|------|--------|------| +| `rust_asr_asrx` | ✅ 實作(asr+diarize 是 pipeline 主力) | - | +| `rust_asrx` / `rust_whisper` | ❌ 不動 | 之後套用同一共用判邏輯(抽出共享函式) | + +### 3.8 順手修正(同 PR) + +| 項目 | 現況 | 修正 | +|------|------|------| +| skip 條件不一致 | pipeline_flows 找 `*.asr_asrx.json`,實際產出 `.asrx.json` | 對齊為實際產出 `*.asrx.json`,否則每次重跑會重做一輪 ASR | + +--- + +## 4. 實作計畫 + +| # | 步驟 | 驗證 | +|---|------|------| +| 1 | 新增第一句亂碼判定(3.2 五項指標) | 單元測試 020 亂碼文字 → 全命中、004 正常文字 → 通過 | +| 2 | 語種輪詢 loop + 短路(3.3) | `cargo test`;以 020.wav 實跑驗證 rotation_hit | +| 3 | VLM rescue(3.4):HTTP client + response 判定 | mock HTTP 服務單元測試;disable 時不發請求 | +| 4 | 輸出 schema 擴充(3.5) | diff 檢查產出 json | +| 5 | config 下發(3.6)+ 總開關 | 開/關往返測試(關閉 = 行為與現在完全相同) | +| 6 | pipeline skip 條件對齊(3.8) | 重跑同一影片不重做 ASR | +| 7 | 回歸:demo 002-020 實跑 | 004 不丟不重試、020 `rotation_hit(ja)`、亂碼不落 tkg | + +**不做範圍**:rust_asrx / rust_whisper 同步改造、場景幀/OCR 型 VLM 裁決(Mode B)、 +POSE 恢復——後續版本。 + +--- + +## 5. 風險與開放問題 + +| # | 風險 | 對策 | +|---|------|------| +| 1 | 判定過緊誤開輪詢(正常句被誤判) | 閾值保守 + 總開關可關;誤判樣本只在觸發時多付輪詢成本 | +| 2 | 輪詢全部 miss 進 VLM 增加 :8080 負載 | 只在輪詢全失敗後觸發(成本後置);併發受 worker 現行控制限制 | +| 3 | llama.cpp audio 為 experimental,品質可能隨版本變動 | 升級 llama.cpp 時回歸測試:004 → 日文轉錄、020 → 拒答 | +| 4 | `vlm_llm_url` 設定錯誤 | 連線失敗即跳過 rescue 層,不影響主要輸出 | +| 5 | 超長 audio(>ctx) | 本次僅做第一句判定;輪詢重轉音訊同現行,不產生新限制 | + +--- + +## 6. 版本歷史 + +| 版本 | 日期 | 變更 | +|------|------|------| +| 1.0 | 2026-11-05 | 初版:判定規則(第一句觸發)、語種輪詢、VLM 直聽 rescue、輸出 schema、config 區塊、實作計畫(OpenCode / Warren)| +| 1.1 | 2026-11-05 | 實作完成(`rust_asr_asrx.rs`):020 → `rotation_hit(ja)`、004 → `auto_ok`(零成本)、輪詢全 miss → `no_intelligible_speech`;pipeline skip 條件對齊 `*.asrx.json`。偏備註:`final_result` 另有 `forced_language`(`--language` 強制時跳過 recovery);VLM 拒答判定用協議字串組(非可調參數);`lang_prob` 僅在 MLX 輸出含此欄位時使用 | diff --git a/tools/cli/rust/src/bin/rust_asr_asrx.rs b/tools/cli/rust/src/bin/rust_asr_asrx.rs index 15921ce2..798cd922 100644 --- a/tools/cli/rust/src/bin/rust_asr_asrx.rs +++ b/tools/cli/rust/src/bin/rust_asr_asrx.rs @@ -1,57 +1,91 @@ -use clap::Parser; use anyhow::{Context, Result}; +use clap::Parser; use serde::{Deserialize, Serialize}; use serde_json::json; +use std::collections::BTreeMap; +use std::io::Write; use std::path::Path; use std::process::Command; use std::time::Instant; -use std::collections::BTreeMap; use rust_processors::asrx::cluster; use rust_processors::asrx::{l2_normalize, Ecapa, Frontend, SAMPLE_RATE}; use rust_processors::vad::AudioReader; +/// Fixed English transcription prompt for VLM audio rescue (verified stable in +/// smoke test 2026-11-05: temp 0.1, 3/3 consistent on clean speech). +const VLM_RESCUE_PROMPT: &str = + "Transcribe exactly what is spoken in this audio. Output only the transcript."; +/// Protocol-level refusal markers from the model (NOT tuning values, safe as constants). +const VLM_REFUSAL_MARKERS: &[&str] = &[ + "cannot transcribe", + "can't transcribe", + "can't hear", + "cannot hear", + "unable to hear", + "no audio", + "no speech", + "cannot fulfill", + "provide the audio", + "provide an audio", + "provide a link", + "didn't receive", + "did not receive", +]; + #[derive(Parser)] #[command(name = "rust_asr_asrx")] -#[command(about = "ASR + Diarization (Rust + MLX Whisper)")] +#[command(about = "ASR + Diarization (Rust + MLX Whisper) with garbled-text recovery")] #[command(version)] struct Cli { /// Input audio/video file #[arg(short, long)] input: String, - + /// Output JSON file #[arg(short, long)] output: String, - + /// Whisper model path #[arg(long, default_value = "/Users/accusys/models/whisper-small-mlx")] model: String, - + /// VAD model path #[arg(long, default_value = "/Users/accusys/models/silero_vad.onnx")] vad_model: String, - - /// Language (auto-detect if not specified) + + /// Force a single language (disables auto-detect AND recovery rotation) #[arg(short, long)] language: Option, - + + /// Garbled recovery: comma-separated language candidates (overrides admin_config) + #[arg(long)] + languages: Option, + + /// Garbled recovery: disable VLM rescue (overrides admin_config) + #[arg(long)] + no_vlm: bool, + + /// Admin config JSON path (default: $MOMENTRY_ADMIN_CONFIG, else /config/admin_config.json) + #[arg(long)] + admin_config: Option, + /// Enable diarization #[arg(long, default_value = "true")] diarize: bool, - + /// ECAPA model path #[arg(long, default_value = "/Users/accusys/models/ecapa_tdnn.onnx")] ecapa_model: String, - + /// ECAPA window file #[arg(long, default_value = "/Users/accusys/models/ecapa_window_400.f32")] window_file: String, - + /// ECAPA mel file #[arg(long, default_value = "/Users/accusys/models/ecapa_mel_201x80.f32")] mel_file: String, - + /// Max speakers #[arg(long, default_value = "10")] max_speakers: usize, @@ -82,41 +116,511 @@ struct AsrSegment { text: String, } +// --------------------------------------------------------------------------- +// Garbled-text recovery configuration (loaded from admin_config.json) +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct FirstSentenceThresholds { + max_top_char_ratio: f64, + min_lang_prob: f64, + min_repeat_slice_repeat: usize, +} + +impl Default for FirstSentenceThresholds { + fn default() -> Self { + Self { + max_top_char_ratio: 0.6, + min_lang_prob: 0.4, + min_repeat_slice_repeat: 5, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct AsrRecoveryConfig { + garbled_check_enabled: bool, + first_sentence_thresholds: FirstSentenceThresholds, + language_candidates: Vec, + vlm_rescue_enabled: bool, + vlm_max_tokens: u32, + vlm_temperature: f64, + vlm_timeout_secs: u64, + vlm_max_audio_secs: u64, +} + +impl Default for AsrRecoveryConfig { + fn default() -> Self { + Self { + // Missing config => current behavior (pure auto), zero risk. + garbled_check_enabled: false, + first_sentence_thresholds: FirstSentenceThresholds::default(), + language_candidates: vec!["ja".into(), "zh".into(), "en".into()], + vlm_rescue_enabled: true, + vlm_max_tokens: 500, + vlm_temperature: 0.1, + vlm_timeout_secs: 120, + vlm_max_audio_secs: 60, + } + } +} + +/// Resolve admin config path: CLI > $MOMENTRY_ADMIN_CONFIG > /config/admin_config.json +/// (mirrors AdminConfigManager::get_default_config_path in +/// /Users/accusys/momentry_core/src/core/admin_config.rs). +fn resolve_admin_config_path(cli: &Cli) -> Option { + if let Some(p) = &cli.admin_config { + return Some(p.clone()); + } + if let Ok(p) = std::env::var("MOMENTRY_ADMIN_CONFIG") { + if !p.is_empty() { + return Some(p); + } + } + std::env::current_dir().ok().map(|cwd| { + cwd.join("config") + .join("admin_config.json") + .to_string_lossy() + .to_string() + }) +} + +/// Load recovery settings from admin_config.json. +/// No asr_config block => garbled_check_enabled=false (current behavior). +/// Language order is config-driven; hard-coded defaults are only the fallback +/// used when the file is missing/unparseable. +fn load_asr_config(cli: &Cli) -> Result<(AsrRecoveryConfig, String)> { + let mut cfg = AsrRecoveryConfig::default(); + let mut vlm_url = "http://localhost:8080/v1/chat/completions".to_string(); + + if let Some(path) = resolve_admin_config_path(cli) { + if Path::new(&path).exists() { + let content = std::fs::read_to_string(&path) + .with_context(|| format!("Failed to read admin config: {}", path))?; + let v: serde_json::Value = serde_json::from_str(&content) + .with_context(|| format!("Failed to parse admin config: {}", path))?; + + match v.get("asr_config") { + Some(a) => match serde_json::from_value::(a.clone()) { + Ok(sec) => cfg = sec, + Err(e) => println!("[ASR-ASRX] WARN bad asr_config block: {} → defaults", e), + }, + None => { + println!("[ASR-ASRX] admin_config has no asr_config block → garbled recovery disabled"); + } + } + + if let Some(u) = v.pointer("/llm_config/chat/url").and_then(|x| x.as_str()) { + vlm_url = u.to_string(); + } + } else { + println!( + "[ASR-ASRX] WARN admin config not found at {} → compiled defaults", + path + ); + } + } + + if cfg.language_candidates.is_empty() { + cfg.language_candidates = vec!["ja".into(), "zh".into(), "en".into()]; + } + + // CLI overrides (manual-testing path only; config remains the main path) + if let Some(l) = &cli.languages { + cfg.language_candidates = l + .split(',') + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect(); + } + if cli.no_vlm { + cfg.vlm_rescue_enabled = false; + } + + Ok((cfg, vlm_url)) +} + +// --------------------------------------------------------------------------- +// First-sentence garbled detection +// --------------------------------------------------------------------------- + +/// Check whether the first segment's text is meaningful. +/// Returns (meaningful, reasons). Any reason hit => garbled. +fn check_first_sentence( + text: &str, + lang_prob: Option, + t: &FirstSentenceThresholds, +) -> (bool, Vec) { + let mut reasons: Vec = Vec::new(); + let trimmed = text.trim(); + if trimmed.is_empty() { + reasons.push("empty_text".to_string()); + return (false, reasons); + } + + let chars: Vec = trimmed.chars().collect(); + let total = chars.len(); + + // #2 top single-character ratio + let mut counts: std::collections::HashMap = std::collections::HashMap::new(); + for c in &chars { + *counts.entry(*c).or_insert(0) += 1; + } + let max_count = counts.values().copied().max().unwrap_or(0); + if total > 0 && (max_count as f64) / (total as f64) > t.max_top_char_ratio { + reasons.push("high_repeat_char".to_string()); + } + + // #3 longest run of identical consecutive 3-char slices + if total >= t.min_repeat_slice_repeat { + let slice_len = 3; + let slices: Vec = chars + .windows(slice_len) + .map(|w| w.iter().collect::()) + .collect(); + let mut longest_run = 1usize; + let mut run = 1usize; + for i in 1..slices.len() { + if slices[i] == slices[i - 1] { + run += 1; + if run > longest_run { + longest_run = run; + } + } else { + run = 1; + } + } + if longest_run >= t.min_repeat_slice_repeat { + reasons.push("repeated_slice".to_string()); + } + } + + // #4 MLX whisper language confidence (when the output provides it) + if let Some(p) = lang_prob { + if p < t.min_lang_prob { + reasons.push("low_lang_prob".to_string()); + } + } + + (reasons.is_empty(), reasons) +} + +fn is_vlm_refusal(text: &str) -> bool { + let lower = text.to_lowercase(); + VLM_REFUSAL_MARKERS.iter().any(|m| lower.contains(m)) +} + +fn truncate_plain(s: &str, max: usize) -> String { + s.chars().take(max).collect() +} + +// --------------------------------------------------------------------------- +// VLM audio rescue (second reference) +// --------------------------------------------------------------------------- + +/// Trim the extracted audio to max seconds for VLM input (8192 ctx budget). +fn prepare_vlm_audio(audio_path: &str, max_secs: u64) -> Result { + let out = format!("/tmp/rust_asr_asrx_vlm_{}.wav", std::process::id()); + let status = Command::new("ffmpeg") + .args(&[ + "-y", + "-i", + audio_path, + "-t", + &max_secs.to_string(), + "-vn", + "-acodec", + "pcm_s16le", + "-ar", + "16000", + "-ac", + "1", + &out, + ]) + .output() + .context("Failed to run ffmpeg for VLM audio prepare")?; + if !status.status.success() { + anyhow::bail!( + "ffmpeg (vlm prep) failed: {}", + String::from_utf8_lossy(&status.stderr) + ); + } + Ok(out) +} + +enum VlmRescueOutcome { + /// VLM produced a meaningful transcript → adopt + Text(String), + /// VLM could not hear any intelligible speech → negative signal + NoSpeech(String), + /// VLM service unavailable / timed out / errored + Unavailable(String), +} + +fn vlm_rescue(audio_path: &str, vlm_url: &str, cfg: &AsrRecoveryConfig) -> VlmRescueOutcome { + match run_vlm_rescue(audio_path, vlm_url, cfg) { + Ok(outcome) => outcome, + Err(e) => VlmRescueOutcome::Unavailable(format!("{}", e)), + } +} + +fn run_vlm_rescue( + audio_path: &str, + vlm_url: &str, + cfg: &AsrRecoveryConfig, +) -> Result { + let trimmed_audio = prepare_vlm_audio(audio_path, cfg.vlm_max_audio_secs)?; + let audio_bytes = std::fs::read(&trimmed_audio) + .with_context(|| format!("Failed to read trimmed audio: {}", trimmed_audio))?; + println!( + "[ASR-ASRX] VLM rescue: {} bytes audio → {}", + audio_bytes.len(), + vlm_url + ); + + use base64::Engine as _; + let audio_b64 = base64::engine::general_purpose::STANDARD.encode(&audio_bytes); + + let body = json!({ + "model": "gemma-4-12b-it", + "messages": [{ + "role": "user", + "content": [ + {"type": "text", "text": VLM_RESCUE_PROMPT}, + {"type": "input_audio", "input_audio": {"data": audio_b64, "format": "wav"}} + ] + }], + "max_tokens": cfg.vlm_max_tokens, + "temperature": cfg.vlm_temperature + }); + + let client = reqwest::blocking::Client::new(); + let resp = client + .post(vlm_url) + .json(&body) + .timeout(std::time::Duration::from_secs(cfg.vlm_timeout_secs)) + .send() + .context("Failed to call VLM API for audio rescue")?; + + if !resp.status().is_success() { + anyhow::bail!("VLM API returned error: {}", resp.status()); + } + + let json: serde_json::Value = resp.json().context("Failed to parse VLM response")?; + let content = json["choices"][0]["message"]["content"] + .as_str() + .unwrap_or("") + .to_string(); + + if content.trim().is_empty() || is_vlm_refusal(&content) { + return Ok(VlmRescueOutcome::NoSpeech(content)); + } + + let (meaningful, reasons) = + check_first_sentence(&content, None, &cfg.first_sentence_thresholds); + if meaningful { + Ok(VlmRescueOutcome::Text(content)) + } else { + println!( + "[ASR-ASRX] VLM rescue answer failed garbled check: {:?}", + reasons + ); + Ok(VlmRescueOutcome::NoSpeech(content)) + } +} + +fn wav_duration_secs(path: &str) -> f64 { + (|| -> Result { + use hound::WavReader; + let reader = WavReader::open(path)?; + let spec = reader.spec(); + Ok(reader.duration() as f64 / spec.sample_rate as f64) + })() + .unwrap_or(0.0) +} + +// --------------------------------------------------------------------------- +// Recovery executor: auto → language rotation → VLM rescue +// --------------------------------------------------------------------------- + +/// Returns (result, final_result_kind, garbled_fallback, vlm_reason, triggered). +fn transcribe_with_recovery( + audio_path: &str, + model: &str, + cfg: &AsrRecoveryConfig, + vlm_url: &str, + attempts: &mut Vec, +) -> Result<(AsrResult, String, bool, Option, bool)> { + // Layer 0: auto-detect + let auto = run_mlx_whisper(audio_path, model, None)?; + let first = auto.segments.first().map(|s| s.text.as_str()).unwrap_or(""); + let (meaningful, reasons) = check_first_sentence(first, None, &cfg.first_sentence_thresholds); + println!( + "[ASR] auto first-sentence check: meaningful={} reasons={:?}", + meaningful, reasons + ); + attempts.push(json!({ + "language": auto.language, + "result": if meaningful { "accepted" } else { "rejected" }, + "reasons": reasons, + "first_sentence": truncate_plain(first, 40) + })); + if meaningful { + return Ok((auto, "auto_ok".to_string(), false, None, false)); + } + + // Layer 1: language rotation (short-circuits on first meaningful hit) + let mut hit: Option = None; + for lang in &cfg.language_candidates { + match run_mlx_whisper(audio_path, model, Some(lang)) { + Err(e) => attempts.push(json!({ + "language": lang, + "result": "failed", + "error": truncate_plain(&format!("{}", e), 200) + })), + Ok(res) => { + let first = res.segments.first().map(|s| s.text.as_str()).unwrap_or(""); + let (m, reasons) = + check_first_sentence(first, None, &cfg.first_sentence_thresholds); + attempts.push(json!({ + "language": lang, + "result": if m { "accepted" } else { "rejected" }, + "reasons": reasons, + "first_sentence": truncate_plain(first, 40) + })); + if m { + println!("[ASR] rotation hit: language={} → adopt", lang); + hit = Some(res); + break; + } + } + } + } + if let Some(res) = hit { + return Ok((res, "rotation_hit".to_string(), true, None, true)); + } + + // Layer 2: VLM second reference (audio direct) + if !cfg.vlm_rescue_enabled { + // Rotation missed and rescue disabled → retain raw auto result + return Ok((auto, "garbled_retained".to_string(), true, None, true)); + } + match vlm_rescue(audio_path, vlm_url, cfg) { + VlmRescueOutcome::Text(text) => { + let dur = wav_duration_secs(audio_path); + let result = AsrResult { + text: text.clone(), + segments: vec![AsrSegment { + id: 0, + start: 0.0, + end: dur, + text, + }], + language: "vlm".to_string(), + }; + attempts.push(json!({ + "language": "vlm", + "result": "accepted" + })); + Ok((result, "vlm_rescue".to_string(), true, None, true)) + } + VlmRescueOutcome::NoSpeech(content) => { + // Retain raw auto result (never output empty); negative signal for tkg + attempts.push(json!({ + "language": "vlm", + "result": "rejected", + "reason": "no_intelligible_speech" + })); + Ok(( + auto, + "no_intelligible_speech".to_string(), + true, + Some(truncate_plain(&content, 200)), + true, + )) + } + VlmRescueOutcome::Unavailable(err) => { + attempts.push(json!({ + "language": "vlm", + "result": "failed", + "error": truncate_plain(&err, 200) + })); + Ok(( + auto, + "garbled_retained".to_string(), + true, + Some(truncate_plain(&err, 200)), + true, + )) + } + } +} + +// --------------------------------------------------------------------------- +// main +// --------------------------------------------------------------------------- + fn main() -> Result<()> { let cli = Cli::parse(); - + println!("[ASR-ASRX] Starting..."); let start_total = Instant::now(); - + let input_path = Path::new(&cli.input); if !input_path.exists() { anyhow::bail!("Input file not found: {}", cli.input); } - + // Step 1: Extract audio (if video) - println!("[1/4] Extracting audio..."); + println!("[1/7] Extracting audio..."); let audio_path = if is_video_file(&cli.input) { extract_audio(&cli.input)? } else { cli.input.clone() }; - + // Step 2: VAD detection - println!("[2/4] VAD detection..."); + println!("[2/7] VAD detection..."); let vad_segments = run_vad(&audio_path, &cli.vad_model)?; println!("[VAD] Found {} speech segments", vad_segments.len()); - - // Step 3: ASR transcription - println!("[3/6] ASR transcription..."); - let asr_result = run_mlx_whisper(&audio_path, &cli.model, cli.language.as_deref())?; + + // Step 3: Config for garbled recovery (admin_config.json is the source of truth) + println!("[3/7] Loading recovery config..."); + let (asr_cfg, vlm_url) = load_asr_config(&cli)?; + let recovery_enabled = asr_cfg.garbled_check_enabled && cli.language.is_none(); + if recovery_enabled { + println!( + "[ASR-ASRX] garbled recovery ON | rotation order: {:?} | vlm rescue: {} ({})", + asr_cfg.language_candidates, + asr_cfg.vlm_rescue_enabled && !cli.no_vlm, + vlm_url + ); + } + + // Step 4: ASR transcription (with recovery layers) + println!("[4/7] ASR transcription..."); + let mut attempts: Vec = Vec::new(); + + let (asr_result, final_result_kind, garbled_fallback, vlm_reason, triggered_recovery) = + if !asr_cfg.garbled_check_enabled { + // Current behavior (no check): single run, auto or forced language + let r = run_mlx_whisper(&audio_path, &cli.model, cli.language.as_deref())?; + (r, "auto_ok".to_string(), false, None, false) + } else if cli.language.is_some() { + // Forced language respects the operator; no rotation. + let r = run_mlx_whisper(&audio_path, &cli.model, cli.language.as_deref())?; + (r, "forced_language".to_string(), false, None, false) + } else { + transcribe_with_recovery(&audio_path, &cli.model, &asr_cfg, &vlm_url, &mut attempts)? + }; + println!("[ASR] Language: {}", asr_result.language); println!("[ASR] Segments: {}", asr_result.segments.len()); - - // Step 4: Diarization (if enabled) + + // Step 5: Diarization (if enabled) — unchanged logic, applied to final transcript let segments = if cli.diarize { - println!("[4/6] Computing embeddings..."); - println!("[5/6] Clustering speakers..."); - println!("[6/6] Assigning speaker IDs..."); + println!("[5/7] Computing embeddings..."); + println!("[6/7] Clustering speakers..."); perform_diarization( &audio_path, &asr_result.segments, @@ -126,26 +630,30 @@ fn main() -> Result<()> { cli.max_speakers, )? } else { - println!("[4/6] Skipping diarization..."); - asr_result.segments.iter().enumerate().map(|(i, seg)| { - Segment { + println!("[5/7] Skipping diarization..."); + asr_result + .segments + .iter() + .enumerate() + .map(|(i, seg)| Segment { id: i, start: seg.start, end: seg.end, text: seg.text.clone(), speaker_id: None, is_multi_speaker: false, - } - }).collect() + }) + .collect() }; - + // Count speakers - let n_speakers = segments.iter() + let n_speakers = segments + .iter() .filter_map(|s| s.speaker_id.as_ref()) .map(|s| s.clone()) .collect::>() .len(); - + // Build speaker stats let mut speaker_stats: BTreeMap = BTreeMap::new(); for seg in &segments { @@ -155,12 +663,33 @@ fn main() -> Result<()> { entry.1 += seg.end - seg.start; } } - + let stats_json: serde_json::Value = speaker_stats .into_iter() - .map(|(k, (count, dur))| (k, json!({"count": count, "duration": (dur * 1000.0).round() / 1000.0}))) + .map(|(k, (count, dur))| { + ( + k, + json!({"count": count, "duration": (dur * 1000.0).round() / 1000.0}), + ) + }) .collect(); - + + // Recovery summary block (per design: /Users/accusys/momentry_core/docs_v1.0/DESIGN/ASRX_Garbled_Text_Language_Rotation_V1.0.md) + let recovery = json!({ + "garbled_check_enabled": asr_cfg.garbled_check_enabled, + "triggered": triggered_recovery, + "final_result": final_result_kind, + "language_candidates": asr_cfg.language_candidates, + "attempts": attempts, + "vlm_reference": { + "used": final_result_kind == "vlm_rescue", + "mode": "audio_direct", + "llm_url": vlm_url, + "reason": vlm_reason + }, + "no_intelligible_speech": final_result_kind == "no_intelligible_speech" + }); + // Output let output = json!({ "language": asr_result.language, @@ -169,128 +698,174 @@ fn main() -> Result<()> { "segments": segments, "n_speakers": n_speakers, "speaker_stats": stats_json, + "garbled_fallback": garbled_fallback, + "recovery": recovery, "processing_time": { "total": start_total.elapsed().as_secs_f64() } }); - - std::fs::write(&cli.output, serde_json::to_string_pretty(&output)?)?; + + // Print summary + println!("[7/7] Writing output..."); + print_recovery_summary(&final_result_kind, &attempts, garbled_fallback); + + let mut f = std::fs::File::create(&cli.output)?; + f.write_all(serde_json::to_string_pretty(&output)?.as_bytes())?; println!("[ASR-ASRX] Output: {}", cli.output); - println!("[ASR-ASRX] Done in {:.2}s", start_total.elapsed().as_secs_f32()); - + println!( + "[ASR-ASRX] Done in {:.2}s", + start_total.elapsed().as_secs_f32() + ); + Ok(()) } +fn print_recovery_summary(kind: &str, attempts: &[serde_json::Value], garbled_fallback: bool) { + if garbled_fallback { + println!( + "[ASR-ASRX] recovery.final_result = {} ({} attempts)", + kind, + attempts.len() + ); + } +} + fn is_video_file(path: &str) -> bool { let ext = Path::new(path) .extension() .and_then(|s| s.to_str()) .unwrap_or(""); - + matches!(ext.to_lowercase().as_str(), "mp4" | "mkv" | "avi" | "mov") } fn extract_audio(input: &str) -> Result { let output = input.replace(".mp4", ".wav").replace(".mkv", ".wav"); - + let status = Command::new("ffmpeg") .args(&[ - "-y", "-i", input, - "-vn", "-acodec", "pcm_s16le", - "-ar", "16000", "-ac", "1", - &output + "-y", + "-i", + input, + "-vn", + "-acodec", + "pcm_s16le", + "-ar", + "16000", + "-ac", + "1", + &output, ]) .status() .context("Failed to run ffmpeg")?; - + if !status.success() { anyhow::bail!("ffmpeg failed"); } - + Ok(output) } fn run_vad(audio_path: &str, vad_model: &str) -> Result> { let binary = "/Users/accusys/momentry_core/tools/cli/rust/target/release/rust_vad"; - + let output = Command::new(binary) - .args(&["--audio", audio_path, "--model", vad_model, "--format", "json"]) + .args(&[ + "--audio", audio_path, "--model", vad_model, "--format", "json", + ]) .output() .context("Failed to run rust_vad")?; - + if !output.status.success() { - anyhow::bail!("rust_vad failed: {}", String::from_utf8_lossy(&output.stderr)); + anyhow::bail!( + "rust_vad failed: {}", + String::from_utf8_lossy(&output.stderr) + ); } - + let stdout = String::from_utf8_lossy(&output.stdout); - let json_str = stdout.lines() + let json_str = stdout + .lines() .skip_while(|line| !line.starts_with('{')) .collect::>() .join("\n"); - - let json: serde_json::Value = serde_json::from_str(&json_str) - .context("Failed to parse VAD JSON")?; - let segments = json["segments"] - .as_array() - .context("Invalid VAD output")?; - - Ok(segments.iter().map(|s| { - let start = s["start"].as_f64().unwrap(); - let end = s["end"].as_f64().unwrap(); - (start, end) - }).collect()) + + let json: serde_json::Value = + serde_json::from_str(&json_str).context("Failed to parse VAD JSON")?; + let segments = json["segments"].as_array().context("Invalid VAD output")?; + + Ok(segments + .iter() + .map(|s| { + let start = s["start"].as_f64().unwrap(); + let end = s["end"].as_f64().unwrap(); + (start, end) + }) + .collect()) } fn run_mlx_whisper(audio_path: &str, model: &str, language: Option<&str>) -> Result { let mut args = vec![ audio_path.to_string(), - "--model".to_string(), model.to_string(), - "--output-format".to_string(), "json".to_string(), + "--model".to_string(), + model.to_string(), + "--output-format".to_string(), + "json".to_string(), ]; - + if let Some(lang) = language { args.push("--language".to_string()); args.push(lang.to_string()); } - + let output = Command::new("/opt/homebrew/bin/mlx_whisper") .args(&args) .current_dir("/tmp") .output() .context("Failed to run mlx_whisper")?; - + if !output.status.success() { - anyhow::bail!("mlx_whisper failed: {}", String::from_utf8_lossy(&output.stderr)); + anyhow::bail!( + "mlx_whisper failed: {}", + String::from_utf8_lossy(&output.stderr) + ); } - + let output_file = Path::new(audio_path) .file_stem() .and_then(|s| s.to_str()) .unwrap(); - + let json_path = format!("/tmp/{}.json", output_file); - let json_content = std::fs::read_to_string(&json_path) - .context("Failed to read MLX Whisper output")?; - + if !Path::new(&json_path).exists() { + anyhow::bail!( + "mlx_whisper output not found at {}: whisper printed nothing / language '{}' produced empty transcript", + json_path, + language.unwrap_or("auto") + ); + } + let json_content = + std::fs::read_to_string(&json_path).context("Failed to read MLX Whisper output")?; + let json: serde_json::Value = serde_json::from_str(&json_content)?; - + let segments = json["segments"] .as_array() - .context("Invalid MLX Whisper output")? + .unwrap_or(&Vec::new()) .iter() .enumerate() .map(|(i, s)| AsrSegment { id: i, - start: s["start"].as_f64().unwrap(), - end: s["end"].as_f64().unwrap(), - text: s["text"].as_str().unwrap().to_string(), + start: s["start"].as_f64().unwrap_or(0.0), + end: s["end"].as_f64().unwrap_or(0.0), + text: s["text"].as_str().unwrap_or("").to_string(), }) .collect(); - + Ok(AsrResult { - text: json["text"].as_str().unwrap().to_string(), + text: json["text"].as_str().unwrap_or("").to_string(), segments, - language: json["language"].as_str().unwrap().to_string(), + language: json["language"].as_str().unwrap_or("unknown").to_string(), }) } @@ -303,46 +878,45 @@ fn perform_diarization( max_speakers: usize, ) -> Result> { // Load audio - let audio = AudioReader::from_wav(audio_path) - .context("Failed to read audio for diarization")?; + let audio = + AudioReader::from_wav(audio_path).context("Failed to read audio for diarization")?; let samples = audio.samples(); - + // Initialize ECAPA - let mut frontend = Frontend::new(window_file, mel_file) - .context("Failed to load ASRX frontend")?; - let mut ecapa = Ecapa::new(ecapa_model) - .context("Failed to load ECAPA model")?; - + let mut frontend = + Frontend::new(window_file, mel_file).context("Failed to load ASRX frontend")?; + let mut ecapa = Ecapa::new(ecapa_model).context("Failed to load ECAPA model")?; + // Compute embeddings for each segment let mut embeddings: Vec> = Vec::with_capacity(asr_segments.len()); - + for seg in asr_segments { let a = (seg.start * SAMPLE_RATE as f64) as usize; let b = ((seg.end * SAMPLE_RATE as f64) as usize).min(samples.len()); - + let seg_audio = if b > a { &samples[a..b] } else { &samples[0..0] }; - + let (feats, n_frames) = frontend.compute_feats(seg_audio); let mut emb = if n_frames > 0 { ecapa.embed(&feats, n_frames)? } else { vec![0f32; 192] }; - + l2_normalize(&mut emb); embeddings.push(emb); } - + // Clustering let distances = cluster::cosine_distances(&embeddings); let n_est = cluster::estimate_n_speakers(&distances, max_speakers); let k = n_est.min(asr_segments.len()).max(1); let labels = cluster::agglomerative(&distances, k); - + // Build segments with speaker IDs let segments: Vec = asr_segments .iter() @@ -356,19 +930,22 @@ fn perform_diarization( is_multi_speaker: false, }) .collect(); - + Ok(segments) } fn combine_vad_asr(vad_segments: &[(f64, f64)], asr_result: &AsrResult) -> Vec { - asr_result.segments.iter().enumerate().map(|(i, asr_seg)| { - Segment { + asr_result + .segments + .iter() + .enumerate() + .map(|(i, asr_seg)| Segment { id: i, start: asr_seg.start, end: asr_seg.end, text: asr_seg.text.clone(), speaker_id: None, is_multi_speaker: false, - } - }).collect() -} \ No newline at end of file + }) + .collect() +}