feat: asrx garbled text recovery - first-sentence trigger, config-driven language rotation, VLM audio rescue
- 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)
This commit is contained in:
@@ -120,7 +120,7 @@
|
|||||||
"usage_notes": "Combines ASR and Diarization in one processor. Uses verified whisper-small-mlx model."
|
"usage_notes": "Combines ASR and Diarization in one processor. Uses verified whisper-small-mlx model."
|
||||||
},
|
},
|
||||||
"condition": {
|
"condition": {
|
||||||
"skip_if_exists": "*.asr_asrx.json"
|
"skip_if_exists": "*.asrx.json"
|
||||||
},
|
},
|
||||||
"on_failure": "continue"
|
"on_failure": "continue"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -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 <L>` 參數存在,未指定時 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 <L>`;音訊不重擷取 |
|
||||||
|
| 成本 | 每輪與 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":"<base64>","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 輸出含此欄位時使用 |
|
||||||
@@ -1,19 +1,41 @@
|
|||||||
use clap::Parser;
|
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
|
use clap::Parser;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::io::Write;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
use std::collections::BTreeMap;
|
|
||||||
|
|
||||||
use rust_processors::asrx::cluster;
|
use rust_processors::asrx::cluster;
|
||||||
use rust_processors::asrx::{l2_normalize, Ecapa, Frontend, SAMPLE_RATE};
|
use rust_processors::asrx::{l2_normalize, Ecapa, Frontend, SAMPLE_RATE};
|
||||||
use rust_processors::vad::AudioReader;
|
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)]
|
#[derive(Parser)]
|
||||||
#[command(name = "rust_asr_asrx")]
|
#[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)]
|
#[command(version)]
|
||||||
struct Cli {
|
struct Cli {
|
||||||
/// Input audio/video file
|
/// Input audio/video file
|
||||||
@@ -32,10 +54,22 @@ struct Cli {
|
|||||||
#[arg(long, default_value = "/Users/accusys/models/silero_vad.onnx")]
|
#[arg(long, default_value = "/Users/accusys/models/silero_vad.onnx")]
|
||||||
vad_model: String,
|
vad_model: String,
|
||||||
|
|
||||||
/// Language (auto-detect if not specified)
|
/// Force a single language (disables auto-detect AND recovery rotation)
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
language: Option<String>,
|
language: Option<String>,
|
||||||
|
|
||||||
|
/// Garbled recovery: comma-separated language candidates (overrides admin_config)
|
||||||
|
#[arg(long)]
|
||||||
|
languages: Option<String>,
|
||||||
|
|
||||||
|
/// Garbled recovery: disable VLM rescue (overrides admin_config)
|
||||||
|
#[arg(long)]
|
||||||
|
no_vlm: bool,
|
||||||
|
|
||||||
|
/// Admin config JSON path (default: $MOMENTRY_ADMIN_CONFIG, else <cwd>/config/admin_config.json)
|
||||||
|
#[arg(long)]
|
||||||
|
admin_config: Option<String>,
|
||||||
|
|
||||||
/// Enable diarization
|
/// Enable diarization
|
||||||
#[arg(long, default_value = "true")]
|
#[arg(long, default_value = "true")]
|
||||||
diarize: bool,
|
diarize: bool,
|
||||||
@@ -82,6 +116,450 @@ struct AsrSegment {
|
|||||||
text: String,
|
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<String>,
|
||||||
|
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 > <cwd>/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<String> {
|
||||||
|
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::<AsrRecoveryConfig>(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<f64>,
|
||||||
|
t: &FirstSentenceThresholds,
|
||||||
|
) -> (bool, Vec<String>) {
|
||||||
|
let mut reasons: Vec<String> = Vec::new();
|
||||||
|
let trimmed = text.trim();
|
||||||
|
if trimmed.is_empty() {
|
||||||
|
reasons.push("empty_text".to_string());
|
||||||
|
return (false, reasons);
|
||||||
|
}
|
||||||
|
|
||||||
|
let chars: Vec<char> = trimmed.chars().collect();
|
||||||
|
let total = chars.len();
|
||||||
|
|
||||||
|
// #2 top single-character ratio
|
||||||
|
let mut counts: std::collections::HashMap<char, usize> = 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<String> = chars
|
||||||
|
.windows(slice_len)
|
||||||
|
.map(|w| w.iter().collect::<String>())
|
||||||
|
.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<String> {
|
||||||
|
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<VlmRescueOutcome> {
|
||||||
|
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<f64> {
|
||||||
|
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<serde_json::Value>,
|
||||||
|
) -> Result<(AsrResult, String, bool, Option<String>, 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<AsrResult> = 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<()> {
|
fn main() -> Result<()> {
|
||||||
let cli = Cli::parse();
|
let cli = Cli::parse();
|
||||||
|
|
||||||
@@ -94,7 +572,7 @@ fn main() -> Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Step 1: Extract audio (if video)
|
// 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) {
|
let audio_path = if is_video_file(&cli.input) {
|
||||||
extract_audio(&cli.input)?
|
extract_audio(&cli.input)?
|
||||||
} else {
|
} else {
|
||||||
@@ -102,21 +580,47 @@ fn main() -> Result<()> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Step 2: VAD detection
|
// Step 2: VAD detection
|
||||||
println!("[2/4] VAD detection...");
|
println!("[2/7] VAD detection...");
|
||||||
let vad_segments = run_vad(&audio_path, &cli.vad_model)?;
|
let vad_segments = run_vad(&audio_path, &cli.vad_model)?;
|
||||||
println!("[VAD] Found {} speech segments", vad_segments.len());
|
println!("[VAD] Found {} speech segments", vad_segments.len());
|
||||||
|
|
||||||
// Step 3: ASR transcription
|
// Step 3: Config for garbled recovery (admin_config.json is the source of truth)
|
||||||
println!("[3/6] ASR transcription...");
|
println!("[3/7] Loading recovery config...");
|
||||||
let asr_result = run_mlx_whisper(&audio_path, &cli.model, cli.language.as_deref())?;
|
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<serde_json::Value> = 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] Language: {}", asr_result.language);
|
||||||
println!("[ASR] Segments: {}", asr_result.segments.len());
|
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 {
|
let segments = if cli.diarize {
|
||||||
println!("[4/6] Computing embeddings...");
|
println!("[5/7] Computing embeddings...");
|
||||||
println!("[5/6] Clustering speakers...");
|
println!("[6/7] Clustering speakers...");
|
||||||
println!("[6/6] Assigning speaker IDs...");
|
|
||||||
perform_diarization(
|
perform_diarization(
|
||||||
&audio_path,
|
&audio_path,
|
||||||
&asr_result.segments,
|
&asr_result.segments,
|
||||||
@@ -126,21 +630,25 @@ fn main() -> Result<()> {
|
|||||||
cli.max_speakers,
|
cli.max_speakers,
|
||||||
)?
|
)?
|
||||||
} else {
|
} else {
|
||||||
println!("[4/6] Skipping diarization...");
|
println!("[5/7] Skipping diarization...");
|
||||||
asr_result.segments.iter().enumerate().map(|(i, seg)| {
|
asr_result
|
||||||
Segment {
|
.segments
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, seg)| Segment {
|
||||||
id: i,
|
id: i,
|
||||||
start: seg.start,
|
start: seg.start,
|
||||||
end: seg.end,
|
end: seg.end,
|
||||||
text: seg.text.clone(),
|
text: seg.text.clone(),
|
||||||
speaker_id: None,
|
speaker_id: None,
|
||||||
is_multi_speaker: false,
|
is_multi_speaker: false,
|
||||||
}
|
})
|
||||||
}).collect()
|
.collect()
|
||||||
};
|
};
|
||||||
|
|
||||||
// Count speakers
|
// Count speakers
|
||||||
let n_speakers = segments.iter()
|
let n_speakers = segments
|
||||||
|
.iter()
|
||||||
.filter_map(|s| s.speaker_id.as_ref())
|
.filter_map(|s| s.speaker_id.as_ref())
|
||||||
.map(|s| s.clone())
|
.map(|s| s.clone())
|
||||||
.collect::<std::collections::HashSet<_>>()
|
.collect::<std::collections::HashSet<_>>()
|
||||||
@@ -158,9 +666,30 @@ fn main() -> Result<()> {
|
|||||||
|
|
||||||
let stats_json: serde_json::Value = speaker_stats
|
let stats_json: serde_json::Value = speaker_stats
|
||||||
.into_iter()
|
.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();
|
.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
|
// Output
|
||||||
let output = json!({
|
let output = json!({
|
||||||
"language": asr_result.language,
|
"language": asr_result.language,
|
||||||
@@ -169,18 +698,38 @@ fn main() -> Result<()> {
|
|||||||
"segments": segments,
|
"segments": segments,
|
||||||
"n_speakers": n_speakers,
|
"n_speakers": n_speakers,
|
||||||
"speaker_stats": stats_json,
|
"speaker_stats": stats_json,
|
||||||
|
"garbled_fallback": garbled_fallback,
|
||||||
|
"recovery": recovery,
|
||||||
"processing_time": {
|
"processing_time": {
|
||||||
"total": start_total.elapsed().as_secs_f64()
|
"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] 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(())
|
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 {
|
fn is_video_file(path: &str) -> bool {
|
||||||
let ext = Path::new(path)
|
let ext = Path::new(path)
|
||||||
.extension()
|
.extension()
|
||||||
@@ -195,10 +744,17 @@ fn extract_audio(input: &str) -> Result<String> {
|
|||||||
|
|
||||||
let status = Command::new("ffmpeg")
|
let status = Command::new("ffmpeg")
|
||||||
.args(&[
|
.args(&[
|
||||||
"-y", "-i", input,
|
"-y",
|
||||||
"-vn", "-acodec", "pcm_s16le",
|
"-i",
|
||||||
"-ar", "16000", "-ac", "1",
|
input,
|
||||||
&output
|
"-vn",
|
||||||
|
"-acodec",
|
||||||
|
"pcm_s16le",
|
||||||
|
"-ar",
|
||||||
|
"16000",
|
||||||
|
"-ac",
|
||||||
|
"1",
|
||||||
|
&output,
|
||||||
])
|
])
|
||||||
.status()
|
.status()
|
||||||
.context("Failed to run ffmpeg")?;
|
.context("Failed to run ffmpeg")?;
|
||||||
@@ -214,38 +770,47 @@ fn run_vad(audio_path: &str, vad_model: &str) -> Result<Vec<(f64, f64)>> {
|
|||||||
let binary = "/Users/accusys/momentry_core/tools/cli/rust/target/release/rust_vad";
|
let binary = "/Users/accusys/momentry_core/tools/cli/rust/target/release/rust_vad";
|
||||||
|
|
||||||
let output = Command::new(binary)
|
let output = Command::new(binary)
|
||||||
.args(&["--audio", audio_path, "--model", vad_model, "--format", "json"])
|
.args(&[
|
||||||
|
"--audio", audio_path, "--model", vad_model, "--format", "json",
|
||||||
|
])
|
||||||
.output()
|
.output()
|
||||||
.context("Failed to run rust_vad")?;
|
.context("Failed to run rust_vad")?;
|
||||||
|
|
||||||
if !output.status.success() {
|
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 stdout = String::from_utf8_lossy(&output.stdout);
|
||||||
let json_str = stdout.lines()
|
let json_str = stdout
|
||||||
|
.lines()
|
||||||
.skip_while(|line| !line.starts_with('{'))
|
.skip_while(|line| !line.starts_with('{'))
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.join("\n");
|
.join("\n");
|
||||||
|
|
||||||
let json: serde_json::Value = serde_json::from_str(&json_str)
|
let json: serde_json::Value =
|
||||||
.context("Failed to parse VAD JSON")?;
|
serde_json::from_str(&json_str).context("Failed to parse VAD JSON")?;
|
||||||
let segments = json["segments"]
|
let segments = json["segments"].as_array().context("Invalid VAD output")?;
|
||||||
.as_array()
|
|
||||||
.context("Invalid VAD output")?;
|
|
||||||
|
|
||||||
Ok(segments.iter().map(|s| {
|
Ok(segments
|
||||||
let start = s["start"].as_f64().unwrap();
|
.iter()
|
||||||
let end = s["end"].as_f64().unwrap();
|
.map(|s| {
|
||||||
(start, end)
|
let start = s["start"].as_f64().unwrap();
|
||||||
}).collect())
|
let end = s["end"].as_f64().unwrap();
|
||||||
|
(start, end)
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run_mlx_whisper(audio_path: &str, model: &str, language: Option<&str>) -> Result<AsrResult> {
|
fn run_mlx_whisper(audio_path: &str, model: &str, language: Option<&str>) -> Result<AsrResult> {
|
||||||
let mut args = vec![
|
let mut args = vec![
|
||||||
audio_path.to_string(),
|
audio_path.to_string(),
|
||||||
"--model".to_string(), model.to_string(),
|
"--model".to_string(),
|
||||||
"--output-format".to_string(), "json".to_string(),
|
model.to_string(),
|
||||||
|
"--output-format".to_string(),
|
||||||
|
"json".to_string(),
|
||||||
];
|
];
|
||||||
|
|
||||||
if let Some(lang) = language {
|
if let Some(lang) = language {
|
||||||
@@ -260,7 +825,10 @@ fn run_mlx_whisper(audio_path: &str, model: &str, language: Option<&str>) -> Res
|
|||||||
.context("Failed to run mlx_whisper")?;
|
.context("Failed to run mlx_whisper")?;
|
||||||
|
|
||||||
if !output.status.success() {
|
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)
|
let output_file = Path::new(audio_path)
|
||||||
@@ -269,28 +837,35 @@ fn run_mlx_whisper(audio_path: &str, model: &str, language: Option<&str>) -> Res
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let json_path = format!("/tmp/{}.json", output_file);
|
let json_path = format!("/tmp/{}.json", output_file);
|
||||||
let json_content = std::fs::read_to_string(&json_path)
|
if !Path::new(&json_path).exists() {
|
||||||
.context("Failed to read MLX Whisper output")?;
|
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 json: serde_json::Value = serde_json::from_str(&json_content)?;
|
||||||
|
|
||||||
let segments = json["segments"]
|
let segments = json["segments"]
|
||||||
.as_array()
|
.as_array()
|
||||||
.context("Invalid MLX Whisper output")?
|
.unwrap_or(&Vec::new())
|
||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.map(|(i, s)| AsrSegment {
|
.map(|(i, s)| AsrSegment {
|
||||||
id: i,
|
id: i,
|
||||||
start: s["start"].as_f64().unwrap(),
|
start: s["start"].as_f64().unwrap_or(0.0),
|
||||||
end: s["end"].as_f64().unwrap(),
|
end: s["end"].as_f64().unwrap_or(0.0),
|
||||||
text: s["text"].as_str().unwrap().to_string(),
|
text: s["text"].as_str().unwrap_or("").to_string(),
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
Ok(AsrResult {
|
Ok(AsrResult {
|
||||||
text: json["text"].as_str().unwrap().to_string(),
|
text: json["text"].as_str().unwrap_or("").to_string(),
|
||||||
segments,
|
segments,
|
||||||
language: json["language"].as_str().unwrap().to_string(),
|
language: json["language"].as_str().unwrap_or("unknown").to_string(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -303,15 +878,14 @@ fn perform_diarization(
|
|||||||
max_speakers: usize,
|
max_speakers: usize,
|
||||||
) -> Result<Vec<Segment>> {
|
) -> Result<Vec<Segment>> {
|
||||||
// Load audio
|
// Load audio
|
||||||
let audio = AudioReader::from_wav(audio_path)
|
let audio =
|
||||||
.context("Failed to read audio for diarization")?;
|
AudioReader::from_wav(audio_path).context("Failed to read audio for diarization")?;
|
||||||
let samples = audio.samples();
|
let samples = audio.samples();
|
||||||
|
|
||||||
// Initialize ECAPA
|
// Initialize ECAPA
|
||||||
let mut frontend = Frontend::new(window_file, mel_file)
|
let mut frontend =
|
||||||
.context("Failed to load ASRX frontend")?;
|
Frontend::new(window_file, mel_file).context("Failed to load ASRX frontend")?;
|
||||||
let mut ecapa = Ecapa::new(ecapa_model)
|
let mut ecapa = Ecapa::new(ecapa_model).context("Failed to load ECAPA model")?;
|
||||||
.context("Failed to load ECAPA model")?;
|
|
||||||
|
|
||||||
// Compute embeddings for each segment
|
// Compute embeddings for each segment
|
||||||
let mut embeddings: Vec<Vec<f32>> = Vec::with_capacity(asr_segments.len());
|
let mut embeddings: Vec<Vec<f32>> = Vec::with_capacity(asr_segments.len());
|
||||||
@@ -361,14 +935,17 @@ fn perform_diarization(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn combine_vad_asr(vad_segments: &[(f64, f64)], asr_result: &AsrResult) -> Vec<Segment> {
|
fn combine_vad_asr(vad_segments: &[(f64, f64)], asr_result: &AsrResult) -> Vec<Segment> {
|
||||||
asr_result.segments.iter().enumerate().map(|(i, asr_seg)| {
|
asr_result
|
||||||
Segment {
|
.segments
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, asr_seg)| Segment {
|
||||||
id: i,
|
id: i,
|
||||||
start: asr_seg.start,
|
start: asr_seg.start,
|
||||||
end: asr_seg.end,
|
end: asr_seg.end,
|
||||||
text: asr_seg.text.clone(),
|
text: asr_seg.text.clone(),
|
||||||
speaker_id: None,
|
speaker_id: None,
|
||||||
is_multi_speaker: false,
|
is_multi_speaker: false,
|
||||||
}
|
})
|
||||||
}).collect()
|
.collect()
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user