diff --git a/README.en.md b/README.en.md index 7caa777..e1097b1 100644 --- a/README.en.md +++ b/README.en.md @@ -27,7 +27,7 @@ VRCMC is a VRChat Chatbox companion built with Kotlin Multiplatform and Compose - **VRChat Chatbox**: Send messages over OSC to VRChat on the same computer or local network. Save multiple devices and switch between them; desktop and Android builds can also scan the local network. An IP alone defaults to `9000:IP:9001`, or you can specify both ports. The input limit follows Chatbox's 144-character and 9-line limits and the number of output languages; disable dynamic character limiting in Preferences. - **Translation providers**: The API page exposes Qwen, Microsoft Edge Web (Bing), DeepSeek, OpenAI/GPT, and a custom compatible endpoint. Configure an API key, base URL, model, timeout, retries, fallback model, custom headers, and streaming where supported. - **Translation output**: Select up to two target languages, choose whether to show the original, configure line breaks and output order, and optionally send the original before the translation. -- **Voice input**: Use Qwen Fun-ASR cloud recognition. On Windows x64 with AVX2, download Whisper Small or Medium for offline recognition. Desktop builds let you select a microphone; Android requires microphone permission. +- **Voice input**: Use Qwen Fun-ASR cloud recognition. On Windows x64, download SenseVoice Small INT8 or Fun-ASR-Nano INT8 for offline recognition. Desktop builds let you select a microphone; Android uses cloud recognition and requires microphone permission. - **Interpretation**: Use system voice input or app recognition. Simultaneous interpretation follows the VRChat microphone state and sends after mute; Always interpretation sends after input pauses and can merge quick successive messages. - **Listen to others (Windows)**: Click the ear button on the Chat page to capture the Windows default playback device. Speech is detected locally and shown sentence by sentence with the original and one translation in an always-on-top subtitle window. Choose listening and target languages, resize or minimize the window, and adjust opacity. - **SteamVR overlay**: Enable it in subtitle settings and choose the left hand, right hand, or screen center. Hand overlays follow controllers and the center overlay follows the headset. Choose 50%–200% size; opacity is shared with desktop subtitles and ranges from 30%–100%. SteamVR and a connected headset are required. @@ -53,7 +53,7 @@ Edge Web is a public web endpoint that does not require an API key. It is not th - Device information, chat history, application settings, the hotword dictionary, and error logs are stored locally by default. - API keys and custom authentication headers are stored separately from regular settings. Android uses Android Keystore, Windows uses DPAPI, and iOS uses Keychain; other desktop systems do not persist these sensitive values. -- Cloud speech recognition sends recordings to the selected service. Local Whisper processes audio on the device and does not fall back to the cloud. Translation text is sent to the configured translation provider, and Edge TTS sends speech text to Microsoft. +- Cloud speech recognition sends recordings to the selected service. Local recognition models process audio on the device and do not fall back to the cloud. Translation text is sent to the configured translation provider, and Edge TTS sends speech text to Microsoft. - **Listen to others** keeps recognized subtitles in its window only: it does not write them to chat history, send them to VRChat, or read them aloud. It captures the Windows default playback device selected when listening starts; restart listening after switching devices. - Android application data backup is disabled. diff --git a/README.ja.md b/README.ja.md index 1e7b58c..1d7fff8 100644 --- a/README.ja.md +++ b/README.ja.md @@ -27,7 +27,7 @@ VRCMC は、Kotlin Multiplatform と Compose Multiplatform で開発された VR - **VRChat Chatbox**:OSC で同じ PC またはローカルネットワーク上の VRChat にメッセージを送信します。複数のデバイスを保存して切り替えられ、デスクトップ版と Android ではローカルネットワークのスキャンも利用できます。IP だけを入力した場合は `9000:IP:9001` を使用し、送受信ポートも指定できます。入力欄の文字数上限は Chatbox の 144 文字・9 行制限と出力言語数に応じて計算され、設定で動的な文字数制限を無効にできます。 - **翻訳サービス**:API ページで Qwen、Microsoft Edge Web(Bing)、DeepSeek、OpenAI/GPT、カスタム互換エンドポイントを選択できます。サービスに応じて API Key、Base URL、モデル、タイムアウト、再試行、フォールバックモデル、カスタムヘッダー、ストリーミングを設定できます。 - **翻訳出力**:最大 2 つの翻訳先言語を選択し、原文の表示、改行、原文と訳文の順番を設定できます。原文を先に送信することもできます。 -- **音声入力**:Qwen Fun-ASR のクラウド認識を利用できます。Windows x64・AVX2 対応 PC では Whisper Small または Medium をダウンロードしてオフライン認識できます。デスクトップ版ではマイクを選択でき、Android ではマイク権限が必要です。 +- **音声入力**:Qwen Fun-ASR のクラウド認識を利用できます。Windows x64 では SenseVoice Small INT8 または Fun-ASR-Nano INT8 をダウンロードし、オフライン認識できます。デスクトップ版ではマイクを選択でき、Android ではクラウド認識とマイク権限を使用します。 - **同時通訳**:システムの音声入力またはアプリ内認識と連携できます。有効にすると VRChat のマイク状態に応じて録音し、マイクを切った後に翻訳して送信します。「常時通訳」では入力が止まった後に自動送信し、短時間に続けて入力したメッセージを結合できます。 - **相手の声を聞く(Windows)**:チャットページ右上の耳ボタンで Windows の既定の再生デバイスを聞き取り、音声をローカルで検出して、常に手前に表示される字幕ウィンドウに原文と 1 つの訳文を文単位で表示します。聞き取り言語と翻訳先言語、ウィンドウのサイズ・最小化・不透明度を設定できます。 - **SteamVR オーバーレイ**:字幕設定で有効にし、左手・右手・画面中央から位置を選べます。手元のパネルはコントローラーに、画面中央のパネルはヘッドセットに追従します。サイズは 50%–200%、不透明度はデスクトップ字幕と共通の 30%–100% です。SteamVR と接続済みのヘッドセットが必要です。 @@ -53,7 +53,7 @@ Edge Web は API Key 不要の公開ウェブエンドポイントで、Azure AI - デバイス情報、チャット履歴、アプリ設定、ホットワード辞書、エラーログはデフォルトでローカルに保存されます。 - API Key とカスタム認証ヘッダーは通常の設定と分けて保存されます。Android は Android Keystore、Windows は DPAPI、iOS は Keychain を使用し、その他のデスクトップではこれらの機密情報を永続化しません。 -- クラウド音声認識では録音を選択したサービスへ送信します。ローカル Whisper は端末内で音声を処理し、クラウドへ切り替えません。翻訳テキストは設定した翻訳サービスへ、Edge TTS の読み上げテキストは Microsoft へ送信されます。 +- クラウド音声認識では録音を選択したサービスへ送信します。ローカル認識モデルは端末内で音声を処理し、クラウドへ切り替えません。翻訳テキストは設定した翻訳サービスへ、Edge TTS の読み上げテキストは Microsoft へ送信されます。 - 「相手の声を聞く」の字幕はウィンドウ内だけに表示され、チャット履歴への保存、VRChat への送信、読み上げは行いません。聞き取り開始時の Windows 既定の再生デバイスを使用するため、デバイスを切り替えた場合は聞き取りを再開してください。 - Android ではアプリデータのバックアップを無効にしています。 diff --git a/README.md b/README.md index 133773d..1b9b45c 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ VRCMC 是一款基于 Kotlin Multiplatform 与 Compose Multiplatform 开发的 V - **VRChat Chatbox**:通过 OSC 向同一台电脑或局域网中的 VRChat 发送消息。可保存多个设备并切换,桌面版和 Android 还可扫描局域网设备;只填 IP 时使用 `9000:IP:9001`,也可指定收发端口。输入框会根据 Chatbox 的 144 字符、9 行限制和输出语言数量计算字符上限,可在偏好设置中关闭动态字符限制。 - **翻译服务**:API 页面可选择 Qwen、Microsoft Edge Web(Bing)、DeepSeek、OpenAI/GPT 或自定义兼容端点。可按服务支持情况设置 API Key、Base URL、模型、超时、重试、备用模型、自定义请求头和流式响应。 - **翻译输出**:最多选择两种目标语言,设置是否显示原文、换行方式和原文/译文顺序,也可以先发送原文再发送译文。 -- **语音输入**:可使用 Qwen Fun-ASR 云端识别;Windows x64 且支持 AVX2 的设备可下载 Whisper Small 或 Medium,在本地离线识别。桌面版可选择麦克风,Android 需要麦克风权限。 +- **语音输入**:可使用 Qwen Fun-ASR 云端识别;Windows x64 设备可下载 SenseVoice Small INT8 或 Fun-ASR-Nano INT8,在本地离线识别。桌面版可选择麦克风,Android 使用云端识别并需要麦克风权限。 - **同声传译**:可配合系统语音输入或应用内识别。开启后会根据 VRChat 麦克风状态采集语音,闭麦后翻译并发送;“始终传译”会在输入暂停后自动发送,并可合并快速连续消息。 - **听别人说话(Windows)**:点击聊天页右上角的耳朵按钮,监听 Windows 默认播放设备并在本地检测人声,在置顶字幕窗口中按句显示原文和一种译文。窗口可调整大小、最小化和不透明度,设置中可选择听的语言和目标语言。 - **SteamVR 叠加界面**:可在字幕设置中开启,位置支持左手、右手或屏幕中间;手部面板跟随控制器,屏幕中间面板跟随头显。大小可选 50%–200%,与桌面字幕共用 30%–100% 的不透明度,需要 SteamVR 和已连接的头显。 @@ -53,7 +53,7 @@ Edge Web 是无需 API Key 的公共网页接口,不是 Azure AI Translator AP - 设备信息、聊天记录、应用设置、热词字典和错误日志默认保存在本机。 - API Key 和自定义鉴权请求头与普通设置分开保存;Android 使用 Android Keystore,Windows 使用 DPAPI,iOS 使用 Keychain。其他桌面系统不会持久化这些敏感配置。 -- 云端语音识别会将录音发送到所选服务;本地 Whisper 在设备上处理音频,不会回退到云端。翻译文本会发送到配置的翻译服务,Edge TTS 会将朗读文本发送到微软。 +- 云端语音识别会将录音发送到所选服务;本地识别模型在设备上处理音频,不会回退到云端。翻译文本会发送到配置的翻译服务,Edge TTS 会将朗读文本发送到微软。 - “听别人说话”只在字幕窗口显示识别结果,不写入聊天记录、不发送到 VRChat,也不触发朗读;它监听启动时的 Windows 默认播放设备,切换设备后需要重新开启。 - Android 已关闭应用数据备份。 diff --git a/README.zh-TW.md b/README.zh-TW.md index 72f62ad..d9e00b2 100644 --- a/README.zh-TW.md +++ b/README.zh-TW.md @@ -27,7 +27,7 @@ VRCMC 是一款使用 Kotlin Multiplatform 與 Compose Multiplatform 開發的 V - **VRChat Chatbox**:透過 OSC 向同一台電腦或區域網路中的 VRChat 傳送訊息。可儲存多個裝置並切換,桌面版和 Android 也可掃描區域網路裝置;只填 IP 時使用 `9000:IP:9001`,也可指定收發連接埠。輸入框會依 Chatbox 的 144 字元、9 行限制與輸出語言數量計算字元上限,可在偏好設定中關閉動態字元限制。 - **翻譯服務**:API 頁面可選擇 Qwen、Microsoft Edge Web(Bing)、DeepSeek、OpenAI/GPT 或自訂相容端點。可依服務支援情況設定 API Key、Base URL、模型、逾時、重試、備用模型、自訂請求標頭與串流回應。 - **翻譯輸出**:最多選擇兩種目標語言,設定是否顯示原文、換行方式與原文/譯文順序,也可以先傳送原文再傳送譯文。 -- **語音輸入**:可使用 Qwen Fun-ASR 雲端辨識;Windows x64 且支援 AVX2 的裝置可下載 Whisper Small 或 Medium,在本機離線辨識。桌面版可選擇麥克風,Android 需要麥克風權限。 +- **語音輸入**:可使用 Qwen Fun-ASR 雲端辨識;Windows x64 裝置可下載 SenseVoice Small INT8 或 Fun-ASR-Nano INT8,在本機離線辨識。桌面版可選擇麥克風,Android 使用雲端辨識並需要麥克風權限。 - **同聲口譯**:可搭配系統語音輸入或應用程式內辨識。開啟後會依 VRChat 麥克風狀態收音,閉麥後翻譯並傳送;「始終口譯」會在輸入暫停後自動傳送,並可合併快速連續訊息。 - **聽別人說話(Windows)**:點擊聊天頁右上角的耳朵按鈕,監聽 Windows 預設播放裝置並在本機偵測人聲,在置頂字幕視窗中按句顯示原文與一種譯文。視窗可調整大小、最小化與不透明度,設定中可選擇聆聽語言和目標語言。 - **SteamVR 疊加介面**:可在字幕設定中開啟,位置支援左手、右手或螢幕中央;手部面板跟隨控制器,螢幕中央面板跟隨頭顯。大小可選 50%–200%,與桌面字幕共用 30%–100% 的不透明度,需要 SteamVR 和已連接的頭顯。 @@ -53,7 +53,7 @@ Edge Web 是不需要 API Key 的公共網頁端點,不是 Azure AI Translator - 裝置資訊、聊天記錄、應用程式設定、熱詞字典與錯誤日誌預設儲存在本機。 - API Key 與自訂驗證請求標頭會與一般設定分開儲存;Android 使用 Android Keystore、Windows 使用 DPAPI、iOS 使用 Keychain,其他桌面系統不會持久儲存這些敏感設定。 -- 雲端語音辨識會將錄音傳送至所選服務;本機 Whisper 在裝置上處理音訊,不會回退到雲端。翻譯文字會傳送至已設定的翻譯服務,Edge TTS 會將朗讀文字傳送至 Microsoft。 +- 雲端語音辨識會將錄音傳送至所選服務;本機辨識模型在裝置上處理音訊,不會回退到雲端。翻譯文字會傳送至已設定的翻譯服務,Edge TTS 會將朗讀文字傳送至 Microsoft。 - 「聽別人說話」只在字幕視窗顯示辨識結果,不會寫入聊天記錄、傳送至 VRChat 或觸發朗讀;它監聽啟動時的 Windows 預設播放裝置,切換裝置後需要重新開始。 - Android 已關閉應用程式資料備份。 diff --git a/WINDOWS_EXE_PACKAGING.md b/WINDOWS_EXE_PACKAGING.md index bfa3e0e..c0343dd 100644 --- a/WINDOWS_EXE_PACKAGING.md +++ b/WINDOWS_EXE_PACKAGING.md @@ -42,27 +42,32 @@ composeApp\build\compose\binaries\main-release\app\VRCMC\ ### 语音运行库体积优化 -在 Windows x64 上构建时,Gradle 会自动先裁剪 ONNX Runtime 和 Whisper JNI,再交给 ProGuard 和应用打包任务: +在 Windows x64 上构建时,Gradle 会自动先裁剪 ONNX Runtime,再交给 ProGuard 和应用打包任务: - ONNX Runtime:移除 Linux、macOS 本地库及 Windows `.pdb` 调试符号,保留 Windows x64 DLL。 -- Whisper JNI:移除 Debian、macOS 本地库,保留 Windows x64 DLL。 -- 两者的 Java 类、JNI 加载路径和许可证声明均保留,开发运行、桌面测试及 release 打包使用同一份裁剪后的依赖。其他操作系统或 CPU 架构仍使用原始依赖。 +- Java 类、JNI 加载路径和许可证声明均保留,开发运行、桌面测试及 release 打包使用同一份裁剪后的依赖。其他操作系统或 CPU 架构仍使用原始依赖。 -中间产物位于 `composeApp\build\generated\windows-native\`,无需手动修改 Gradle 缓存或打包后的 JAR。Whisper 识别模型仍由用户在应用中下载,不包含在安装包中。 +中间产物位于 `composeApp\build\generated\windows-native\`,无需手动修改 Gradle 缓存或打包后的 JAR。本地识别模型仍由用户在应用中下载,不包含在安装包中。 修改运行库版本或裁剪规则后,除检查最终 EXE 大小外,还应验证实际的 VAD 推理和离线转写: ```powershell .\gradlew.bat :composeApp:desktopTest --tests '*SileroSpeechDetectorTest' -$env:VRCMC_LOCAL_ASR_INTEGRATION_TEST = '1' +$env:VRCMC_SENSE_VOICE_INTEGRATION_TEST = '1' try { - .\gradlew.bat :composeApp:desktopTest --tests '*LocalWhisperIntegrationTest' + .\gradlew.bat :composeApp:desktopTest --tests '*SenseVoiceRecognitionTest' } finally { - Remove-Item Env:\VRCMC_LOCAL_ASR_INTEGRATION_TEST + Remove-Item Env:\VRCMC_SENSE_VOICE_INTEGRATION_TEST +} +$env:VRCMC_FUN_ASR_INTEGRATION_TEST = '1' +try { + .\gradlew.bat :composeApp:desktopTest --tests '*FunAsrNanoRecognitionTest' +} finally { + Remove-Item Env:\VRCMC_FUN_ASR_INTEGRATION_TEST } ``` -离线转写测试需要支持 AVX2 的 Windows x64 CPU;首次执行会下载并校验约 190 MB 的模型,缓存于 `composeApp\build\local-asr-test\`,不会进入安装包。 +离线转写测试需要 Windows x64 CPU,并会校验约 240 MB 的 INT8 模型及词表,这些文件不会进入安装包。 ## 3. 使用仓库内 Inno Setup 打包 diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index 689d89d..cc4a3a5 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -59,10 +59,6 @@ val desktopOnnxRuntime = desktopNativeRuntime( "ai/onnxruntime/native/osx-*/**", "ai/onnxruntime/native/**/*.pdb", ) -val desktopWhisperRuntime = desktopNativeRuntime( - "stripWhisperNatives", libs.whisper.jni, - "debian-*/**", "macos-*/**", -) kotlin { jvm("desktop"); androidTarget(); iosX64(); iosArm64(); iosSimulatorArm64(); sourceSets { commonMain.dependencies { @@ -76,7 +72,8 @@ kotlin { jvm("desktop"); androidTarget(); iosX64(); iosArm64(); iosSimulatorArm6 commonTest.dependencies { implementation(kotlin("test")) } named("desktopMain") { kotlin.srcDir("src/jvmMain/kotlin") - dependencies { implementation(libs.jlayer); implementation(desktopOnnxRuntime); implementation(desktopWhisperRuntime) } + kotlin.srcDir("src/jvmLocalMain/kotlin") + dependencies { implementation(libs.jlayer); implementation(desktopOnnxRuntime) } dependencies { implementation(libs.lwjgl.core) implementation(libs.lwjgl.openvr) diff --git a/composeApp/proguard-rules.pro b/composeApp/proguard-rules.pro index 66e80aa..9d5717e 100644 --- a/composeApp/proguard-rules.pro +++ b/composeApp/proguard-rules.pro @@ -23,9 +23,6 @@ # MethodHandle.invokeExact has JVM signature-polymorphic overloads that ProGuard cannot resolve. -dontwarn ai.onnxruntime.platform.Fp16Conversions -# Whisper JNI looks up parameter fields and callbacks by their original names. --keep class io.github.givimad.whisperjni.** { *; } - # Persisted enum names are restored with valueOf at runtime. -keepclassmembers enum * { public static **[] values(); diff --git a/composeApp/src/commonMain/kotlin/com/vrcmc/app/audio/LocalSpeechModelController.kt b/composeApp/src/commonMain/kotlin/com/vrcmc/app/audio/LocalSpeechModelController.kt index 75aee11..258a6dc 100644 --- a/composeApp/src/commonMain/kotlin/com/vrcmc/app/audio/LocalSpeechModelController.kt +++ b/composeApp/src/commonMain/kotlin/com/vrcmc/app/audio/LocalSpeechModelController.kt @@ -17,9 +17,9 @@ internal class LocalSpeechModelController( private val scope: CoroutineScope, private val recognizer: LocalSpeechRecognizer = localSpeechRecognizer, ) { - private val activeModel = MutableStateFlow(null) - private val modelRevisions = MutableStateFlow>(emptyMap()) - private val downloadJobs = mutableMapOf() + private val activeModel = MutableStateFlow(null) + private val modelRevisions = MutableStateFlow>(emptyMap()) + private val downloadJobs = mutableMapOf() init { scope.launch { @@ -41,12 +41,12 @@ internal class LocalSpeechModelController( } fun updateConfig(config: VoiceInputConfig) { - activeModel.value = config.localWhisperModel.takeIf { - config.enabled && config.provider == VoiceInputProvider.LOCAL_WHISPER + activeModel.value = config.localSpeechModel.takeIf { + config.enabled && config.provider == VoiceInputProvider.LOCAL_MODEL } } - fun downloadModel(model: LocalWhisperModel) { + fun downloadModel(model: LocalSpeechModel) { val previous = downloadJobs[model] if (previous != null && !previous.isCompleted && !previous.isCancelled) return downloadJobs[model] = scope.launch { @@ -59,7 +59,7 @@ internal class LocalSpeechModelController( } } - fun cancelDownload(model: LocalWhisperModel) { + fun cancelDownload(model: LocalSpeechModel) { downloadJobs[model]?.cancel() } } diff --git a/composeApp/src/commonMain/kotlin/com/vrcmc/app/audio/LocalSpeechRecognition.kt b/composeApp/src/commonMain/kotlin/com/vrcmc/app/audio/LocalSpeechRecognition.kt index 83cc1b8..c6546e5 100644 --- a/composeApp/src/commonMain/kotlin/com/vrcmc/app/audio/LocalSpeechRecognition.kt +++ b/composeApp/src/commonMain/kotlin/com/vrcmc/app/audio/LocalSpeechRecognition.kt @@ -2,22 +2,34 @@ package com.vrcmc.app import kotlinx.coroutines.flow.StateFlow -enum class VoiceInputProvider { QWEN, LOCAL_WHISPER } +enum class VoiceInputProvider { + QWEN, + LOCAL_MODEL, + ; + + companion object { + fun fromStoredName(value: String?): VoiceInputProvider = when (value) { + LOCAL_MODEL.name, "LOCAL_WHISPER" -> LOCAL_MODEL + QWEN.name -> QWEN + else -> QWEN + } + } +} -enum class LocalWhisperModel( +enum class LocalSpeechModel( val serializedName: String, val displayName: String, val downloadSizeMb: Int, ) { - SMALL_Q5_1("small-q5_1", "Whisper Small Q5_1", 190), - MEDIUM_Q5_0("medium-q5_0", "Whisper Medium Q5_0", 539), + SENSE_VOICE_SMALL_INT8("sense-voice-small-int8", "SenseVoice Small INT8", 240), + FUN_ASR_NANO_2512_INT8("fun-asr-nano-2512-int8", "Fun-ASR-Nano 2512 INT8", 265), ; val displayLabel: String get() = "$displayName · $downloadSizeMb MB" companion object { - fun fromSerializedName(value: String?): LocalWhisperModel = - entries.firstOrNull { it.serializedName == value } ?: SMALL_Q5_1 + fun fromSerializedName(value: String?): LocalSpeechModel = + entries.firstOrNull { it.serializedName == value } ?: SENSE_VOICE_SMALL_INT8 } } @@ -32,12 +44,12 @@ internal sealed interface LocalSpeechModelStatus { internal interface LocalSpeechRecognizer { val supported: Boolean - fun status(model: LocalWhisperModel): StateFlow + fun status(model: LocalSpeechModel): StateFlow // Only an explicit user action may call this; prepare() only reads the local cache. - suspend fun downloadModel(model: LocalWhisperModel): Boolean - suspend fun prepare(model: LocalWhisperModel): Boolean + suspend fun downloadModel(model: LocalSpeechModel): Boolean + suspend fun prepare(model: LocalSpeechModel): Boolean suspend fun transcribe( - model: LocalWhisperModel, + model: LocalSpeechModel, wav: ByteArray, language: String, ): VoiceTranscriptionResult @@ -48,15 +60,15 @@ internal expect val localSpeechRecognizer: LocalSpeechRecognizer internal fun VoiceInputConfig.hasServiceConfiguration(): Boolean = when (provider) { VoiceInputProvider.QWEN -> apiKey.isNotBlank() && baseUrl.isNotBlank() && model.isNotBlank() - VoiceInputProvider.LOCAL_WHISPER -> localSpeechRecognizer.supported + VoiceInputProvider.LOCAL_MODEL -> localSpeechRecognizer.supported } internal fun voiceInputReadinessFailure(config: VoiceInputConfig): VoiceTranscriptionResult.Failure? = when { - config.provider == VoiceInputProvider.LOCAL_WHISPER && !localSpeechRecognizer.supported -> + config.provider == VoiceInputProvider.LOCAL_MODEL && !localSpeechRecognizer.supported -> VoiceTranscriptionResult.Failure(reason = VoiceTranscriptionFailureReason.LOCAL_UNSUPPORTED) - config.provider == VoiceInputProvider.LOCAL_WHISPER && - localSpeechRecognizer.status(config.localWhisperModel).value != LocalSpeechModelStatus.Ready -> + config.provider == VoiceInputProvider.LOCAL_MODEL && + localSpeechRecognizer.status(config.localSpeechModel).value != LocalSpeechModelStatus.Ready -> VoiceTranscriptionResult.Failure(reason = VoiceTranscriptionFailureReason.LOCAL_MODEL_NOT_READY) config.provider == VoiceInputProvider.QWEN && config.apiKey.isBlank() -> VoiceTranscriptionResult.Failure(reason = VoiceTranscriptionFailureReason.API_KEY_REQUIRED) @@ -76,6 +88,6 @@ internal suspend fun transcribeVoiceAudio( localRecognizer: LocalSpeechRecognizer = localSpeechRecognizer, ): VoiceTranscriptionResult = when (config.provider) { VoiceInputProvider.QWEN -> transcribeQwenAudio(config, wav, onApiFailure) - VoiceInputProvider.LOCAL_WHISPER -> - localRecognizer.transcribe(config.localWhisperModel, wav, config.language) + VoiceInputProvider.LOCAL_MODEL -> + localRecognizer.transcribe(config.localSpeechModel, wav, config.language) } diff --git a/composeApp/src/commonMain/kotlin/com/vrcmc/app/audio/UnsupportedLocalSpeechRecognizer.kt b/composeApp/src/commonMain/kotlin/com/vrcmc/app/audio/UnsupportedLocalSpeechRecognizer.kt index 9098f61..04373d5 100644 --- a/composeApp/src/commonMain/kotlin/com/vrcmc/app/audio/UnsupportedLocalSpeechRecognizer.kt +++ b/composeApp/src/commonMain/kotlin/com/vrcmc/app/audio/UnsupportedLocalSpeechRecognizer.kt @@ -6,10 +6,10 @@ import kotlinx.coroutines.flow.asStateFlow internal object UnsupportedLocalSpeechRecognizer : LocalSpeechRecognizer { override val supported = false private val missing = MutableStateFlow(LocalSpeechModelStatus.Missing).asStateFlow() - override fun status(model: LocalWhisperModel) = missing - override suspend fun downloadModel(model: LocalWhisperModel) = false - override suspend fun prepare(model: LocalWhisperModel) = false - override suspend fun transcribe(model: LocalWhisperModel, wav: ByteArray, language: String) = + override fun status(model: LocalSpeechModel) = missing + override suspend fun downloadModel(model: LocalSpeechModel) = false + override suspend fun prepare(model: LocalSpeechModel) = false + override suspend fun transcribe(model: LocalSpeechModel, wav: ByteArray, language: String) = VoiceTranscriptionResult.Failure(reason = VoiceTranscriptionFailureReason.LOCAL_UNSUPPORTED) override suspend fun release() = Unit } diff --git a/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStrings.kt b/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStrings.kt index 91e5c2e..19ec119 100644 --- a/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStrings.kt +++ b/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStrings.kt @@ -294,18 +294,19 @@ interface LocaleStrings { val voiceInputHint: String get() = "选择云端或本地模型,将录音转换为文字" val qwenVoiceInputHint: String get() = "使用 Fun-ASR 将录音转换为聊天文字" val voiceInputProvider: String get() = "识别服务" - val localWhisper: String get() = "本地 Whisper" + val localModel: String get() = "本地模型" val localModelHint: String get() = "手动下载所选多语言模型后,可按句离线识别,无需 API Key。切换页面、识别服务或关闭语音输入不会中断下载,点击“取消下载”可停止。翻译仍使用已配置的翻译服务。指定识别语言可降低延迟。" + val funAsrNanoHint: String get() = "Fun-ASR-Nano 在复杂场景下更稳健,但会占用更多内存,识别速度也可能较慢。" val localModelDownload: String get() = "下载模型" val localModelCancelDownload: String get() = "取消下载" - val localModelDownloaded: String get() = "模型已下载,启用本地 Whisper 后即可识别" + val localModelDownloaded: String get() = "模型已下载,启用本地模型后即可识别" val localModelPreparing: String get() = "正在准备本地模型…" val localModelDownloading: String get() = "正在下载模型" val localModelReady: String get() = "模型已就绪,可离线识别" val localModelFailed: String get() = "本地模型准备失败,请检查网络或磁盘空间后重试。" val localModelRetry: String get() = "重试" - val localModelUnsupported: String get() = "需要 Windows x64 和支持 AVX2 的处理器" - val localModelNotReady: String get() = "请在 API → 语音输入服务中选择本地 Whisper,点击“下载模型”,完成后启用语音输入。" + val localModelUnsupported: String get() = "本地识别仅在 Windows x64 上可用" + val localModelNotReady: String get() = "请在 API → 语音输入服务中选择本地模型,点击“下载模型”,完成后启用语音输入。" val localRecognitionFailed: String get() = "本地语音识别失败" val qwenApiKey: String get() = "DashScope API Key" val qwenRegion: String get() = "区域" diff --git a/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStringsEn.kt b/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStringsEn.kt index c0eeabe..c353d33 100644 --- a/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStringsEn.kt +++ b/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStringsEn.kt @@ -248,18 +248,19 @@ object LocaleStringsEn : LocaleStrings { override val voiceInputHint = "Choose a cloud or local model to turn recordings into text" override val qwenVoiceInputHint = "Use Fun-ASR to turn recordings into chat text" override val voiceInputProvider = "Recognition service" - override val localWhisper = "Local Whisper" + override val localModel = "Local models" override val localModelHint = "Manually download the selected multilingual model for offline sentence recognition without an API key. Downloads continue when changing pages or services or disabling voice input; use Cancel download to stop. Translation still uses your configured service. Selecting a specific recognition language reduces latency." + override val funAsrNanoHint = "Fun-ASR-Nano is more robust in difficult audio but uses more memory and may be slower." override val localModelDownload = "Download model" override val localModelCancelDownload = "Cancel download" - override val localModelDownloaded = "Model downloaded; enable Local Whisper to recognize speech" + override val localModelDownloaded = "Model downloaded; enable the local model to recognize speech" override val localModelPreparing = "Preparing local model…" override val localModelDownloading = "Downloading model" override val localModelReady = "Model ready for offline recognition" override val localModelFailed = "Could not prepare the local model. Check your network or disk space and retry." override val localModelRetry = "Retry" - override val localModelUnsupported = "Requires Windows x64 and an AVX2-capable processor" - override val localModelNotReady = "Select Local Whisper under API → Voice input service, click Download model, then enable voice input once it finishes." + override val localModelUnsupported = "Local recognition is available only on Windows x64" + override val localModelNotReady = "Select the local model under API → Voice input service, click Download model, then enable voice input once it finishes." override val localRecognitionFailed = "Local speech recognition failed" override val qwenApiKey = "DashScope API Key" override val qwenRegion = "Region" diff --git a/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStringsJa.kt b/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStringsJa.kt index c42779a..38b4574 100644 --- a/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStringsJa.kt +++ b/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStringsJa.kt @@ -303,18 +303,19 @@ object LocaleStringsJa : LocaleStrings { override val voiceInputHint = "クラウドまたはローカルモデルで録音を文字に変換します" override val qwenVoiceInputHint = "Fun-ASR で録音をチャットのテキストに変換します" override val voiceInputProvider = "音声認識サービス" - override val localWhisper = "ローカル Whisper" + override val localModel = "ローカルモデル" override val localModelHint = "選択した多言語モデルを手動でダウンロードすると、API キーなしで文ごとにオフライン認識できます。ページやサービスの切り替え、音声入力の無効化ではダウンロードは中断されません。「ダウンロードをキャンセル」で停止できます。翻訳には設定済みのサービスを使用します。認識言語の指定で遅延を抑えられます。" + override val funAsrNanoHint = "Fun-ASR-Nano は難しい音声に強い一方、より多くのメモリを使用し、認識が遅くなる場合があります。" override val localModelDownload = "モデルをダウンロード" override val localModelCancelDownload = "ダウンロードをキャンセル" - override val localModelDownloaded = "モデルをダウンロード済みです。ローカル Whisper を有効にすると認識できます" + override val localModelDownloaded = "モデルをダウンロード済みです。ローカルモデルを有効にすると認識できます" override val localModelPreparing = "ローカルモデルを準備中…" override val localModelDownloading = "モデルをダウンロード中" override val localModelReady = "モデルの準備完了・オフライン認識が可能です" override val localModelFailed = "モデルの準備に失敗しました。ネットワークやディスク容量を確認して再試行してください。" override val localModelRetry = "再試行" - override val localModelUnsupported = "Windows x64 と AVX2 対応プロセッサーが必要です" - override val localModelNotReady = "API → 音声入力サービスでローカル Whisper を選び、「モデルをダウンロード」を押してください。完了後に音声入力を有効にしてください。" + override val localModelUnsupported = "ローカル認識は Windows x64 でのみ利用できます" + override val localModelNotReady = "API → 音声入力サービスでローカルモデルを選び、「モデルをダウンロード」を押してください。完了後に音声入力を有効にしてください。" override val localRecognitionFailed = "ローカル音声認識に失敗しました" override val qwenApiKey = "DashScope API Key" override val qwenRegion = "リージョン" diff --git a/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStringsZhHans.kt b/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStringsZhHans.kt index af41b21..0c4d448 100644 --- a/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStringsZhHans.kt +++ b/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStringsZhHans.kt @@ -121,18 +121,19 @@ object LocaleStringsZhHans : LocaleStrings { override val voiceInputHint = "选择云端或本地模型,将录音转换为文字" override val qwenVoiceInputHint = "使用 Fun-ASR 将录音转换为聊天文字" override val voiceInputProvider = "识别服务" - override val localWhisper = "本地 Whisper" + override val localModel = "本地模型" override val localModelHint = "手动下载所选多语言模型后,可按句离线识别,无需 API Key。切换页面、识别服务或关闭语音输入不会中断下载,点击“取消下载”可停止。翻译仍使用已配置的翻译服务。指定识别语言可降低延迟。" + override val funAsrNanoHint = "Fun-ASR-Nano 在复杂场景下更稳健,但会占用更多内存,识别速度也可能较慢。" override val localModelDownload = "下载模型" override val localModelCancelDownload = "取消下载" - override val localModelDownloaded = "模型已下载,启用本地 Whisper 后即可识别" + override val localModelDownloaded = "模型已下载,启用本地模型后即可识别" override val localModelPreparing = "正在准备本地模型…" override val localModelDownloading = "正在下载模型" override val localModelReady = "模型已就绪,可离线识别" override val localModelFailed = "本地模型准备失败,请检查网络或磁盘空间后重试。" override val localModelRetry = "重试" - override val localModelUnsupported = "需要 Windows x64 和支持 AVX2 的处理器" - override val localModelNotReady = "请在 API → 语音输入服务中选择本地 Whisper,点击“下载模型”,完成后启用语音输入。" + override val localModelUnsupported = "本地识别仅在 Windows x64 上可用" + override val localModelNotReady = "请在 API → 语音输入服务中选择本地模型,点击“下载模型”,完成后启用语音输入。" override val localRecognitionFailed = "本地语音识别失败" override val qwenApiKey = "DashScope API Key" override val qwenRegion = "区域" diff --git a/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStringsZhHant.kt b/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStringsZhHant.kt index f9c4bdd..a31ea31 100644 --- a/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStringsZhHant.kt +++ b/composeApp/src/commonMain/kotlin/com/vrcmc/app/localization/LocaleStringsZhHant.kt @@ -299,18 +299,19 @@ object LocaleStringsZhHant : LocaleStrings { override val voiceInputHint = "選擇雲端或本機模型,將錄音轉換為文字" override val qwenVoiceInputHint = "使用 Fun-ASR 將錄音轉換為聊天文字" override val voiceInputProvider = "辨識服務" - override val localWhisper = "本機 Whisper" + override val localModel = "本機模型" override val localModelHint = "手動下載所選多語言模型後,可按句離線辨識,無需 API Key。切換頁面、辨識服務或關閉語音輸入不會中斷下載,點擊「取消下載」可停止。翻譯仍使用已設定的翻譯服務。指定辨識語言可降低延遲。" + override val funAsrNanoHint = "Fun-ASR-Nano 在複雜場景下更穩健,但會佔用更多記憶體,辨識速度也可能較慢。" override val localModelDownload = "下載模型" override val localModelCancelDownload = "取消下載" - override val localModelDownloaded = "模型已下載,啟用本機 Whisper 後即可辨識" + override val localModelDownloaded = "模型已下載,啟用本機模型後即可辨識" override val localModelPreparing = "正在準備本機模型…" override val localModelDownloading = "正在下載模型" override val localModelReady = "模型已就緒,可離線辨識" override val localModelFailed = "本機模型準備失敗,請檢查網路或磁碟空間後重試。" override val localModelRetry = "重試" - override val localModelUnsupported = "需要 Windows x64 和支援 AVX2 的處理器" - override val localModelNotReady = "請在 API → 語音輸入服務中選擇本機 Whisper,點擊「下載模型」,完成後啟用語音輸入。" + override val localModelUnsupported = "本機辨識僅在 Windows x64 上可用" + override val localModelNotReady = "請在 API → 語音輸入服務中選擇本機模型,點擊「下載模型」,完成後啟用語音輸入。" override val localRecognitionFailed = "本機語音辨識失敗" override val qwenApiKey = "DashScope API Key" override val qwenRegion = "區域" diff --git a/composeApp/src/commonMain/kotlin/com/vrcmc/app/translation/TranslationSettings.kt b/composeApp/src/commonMain/kotlin/com/vrcmc/app/translation/TranslationSettings.kt index d27d77d..d1ad15f 100644 --- a/composeApp/src/commonMain/kotlin/com/vrcmc/app/translation/TranslationSettings.kt +++ b/composeApp/src/commonMain/kotlin/com/vrcmc/app/translation/TranslationSettings.kt @@ -28,7 +28,7 @@ data class StoredTranslationSettings( data class VoiceInputConfig( val enabled: Boolean = false, val provider: VoiceInputProvider = VoiceInputProvider.QWEN, - val localWhisperModel: LocalWhisperModel = LocalWhisperModel.SMALL_Q5_1, + val localSpeechModel: LocalSpeechModel = LocalSpeechModel.SENSE_VOICE_SMALL_INT8, val apiKey: String = "", val region: String = "singapore", val baseUrl: String = "https://dashscope-intl.aliyuncs.com/api/v1", @@ -80,7 +80,7 @@ fun StoredTranslationSettings.toJson(): String = putJsonObject("voiceInput") { put("enabled", voiceInput.enabled) put("provider", voiceInput.provider.name) - put("localWhisperModel", voiceInput.localWhisperModel.serializedName) + put("localSpeechModel", voiceInput.localSpeechModel.serializedName) put("region", voiceInput.region) put("baseUrl", voiceInput.baseUrl) put("model", voiceInput.model) @@ -237,11 +237,12 @@ fun storedTranslationSettingsFromJson(value: String): StoredTranslationSettings root["voiceInput"]?.jsonObject?.let { obj -> VoiceInputConfig( enabled = obj["enabled"]?.jsonPrimitive?.booleanOrNull ?: false, - provider = VoiceInputProvider.entries.firstOrNull { - it.name == (obj["provider"] as? JsonPrimitive)?.contentOrNull - } ?: VoiceInputProvider.QWEN, - localWhisperModel = LocalWhisperModel.fromSerializedName( - (obj["localWhisperModel"] as? JsonPrimitive)?.contentOrNull, + provider = VoiceInputProvider.fromStoredName( + (obj["provider"] as? JsonPrimitive)?.contentOrNull, + ), + localSpeechModel = LocalSpeechModel.fromSerializedName( + ((obj["localSpeechModel"] ?: obj["localWhisperModel"]) as? JsonPrimitive) + ?.contentOrNull, ), region = obj["region"]?.jsonPrimitive?.contentOrNull ?: "singapore", baseUrl = obj["baseUrl"]?.jsonPrimitive?.contentOrNull diff --git a/composeApp/src/commonMain/kotlin/com/vrcmc/app/ui/components/api/VoiceInputServiceSection.kt b/composeApp/src/commonMain/kotlin/com/vrcmc/app/ui/components/api/VoiceInputServiceSection.kt index 496bbcc..8f2c186 100644 --- a/composeApp/src/commonMain/kotlin/com/vrcmc/app/ui/components/api/VoiceInputServiceSection.kt +++ b/composeApp/src/commonMain/kotlin/com/vrcmc/app/ui/components/api/VoiceInputServiceSection.kt @@ -22,23 +22,25 @@ private val asrRegions = listOf( AsrRegion("custom", "自定义", ""), ) +private val localSpeechLanguages = listOf("auto", "zh", "yue", "ja", "en", "ko") + @Composable internal fun VoiceInputServiceSection( config: VoiceInputConfig, strings: LocaleStrings, onUpdate: ((VoiceInputConfig) -> VoiceInputConfig) -> Unit, - onDownloadLocalModel: (LocalWhisperModel) -> Unit = {}, - onCancelLocalModel: (LocalWhisperModel) -> Unit = {}, + onDownloadLocalModel: (LocalSpeechModel) -> Unit = {}, + onCancelLocalModel: (LocalSpeechModel) -> Unit = {}, localRecognizer: LocalSpeechRecognizer = localSpeechRecognizer, ) { var providerMenu by remember { mutableStateOf(false) } - val localModelStatusFlow = remember(localRecognizer, config.localWhisperModel) { - localRecognizer.status(config.localWhisperModel) + val localModelStatusFlow = remember(localRecognizer, config.localSpeechModel) { + localRecognizer.status(config.localSpeechModel) } val localModelStatus by localModelStatusFlow.collectAsState() val availableProviders = if (localRecognizer.supported) VoiceInputProvider.entries else listOf(VoiceInputProvider.QWEN) val showLocalModel = localRecognizer.supported && ( - config.provider == VoiceInputProvider.LOCAL_WHISPER || + config.provider == VoiceInputProvider.LOCAL_MODEL || localModelStatus is LocalSpeechModelStatus.Downloading || localModelStatus is LocalSpeechModelStatus.Failed ) var showKey by remember { mutableStateOf(false) } @@ -68,13 +70,13 @@ internal fun VoiceInputServiceSection( if (showLocalModel) { HorizontalDivider() LocalSpeechModelSettings( - model = config.localWhisperModel, + model = config.localSpeechModel, status = localModelStatus, supported = localRecognizer.supported, strings = strings, - onModelChange = { model -> onUpdate { it.copy(localWhisperModel = model) } }, - onDownload = { onDownloadLocalModel(config.localWhisperModel) }, - onCancel = { onCancelLocalModel(config.localWhisperModel) }, + onModelChange = { model -> onUpdate { it.copy(localSpeechModel = model) } }, + onDownload = { onDownloadLocalModel(config.localSpeechModel) }, + onCancel = { onCancelLocalModel(config.localSpeechModel) }, ) } return@SettingsCard @@ -91,17 +93,25 @@ internal fun VoiceInputServiceSection( ) { Text(strings.voiceInputProvider, Modifier.weight(1f)) if (config.provider in availableProviders) { - Text(if (config.provider == VoiceInputProvider.QWEN) "Fun-ASR" else strings.localWhisper) + Text(if (config.provider == VoiceInputProvider.QWEN) "Fun-ASR" else strings.localModel) } Icon(Icons.Default.ArrowDropDown, null) } DropdownMenu(providerMenu, { providerMenu = false }) { availableProviders.forEach { provider -> DropdownMenuItem( - text = { Text(if (provider == VoiceInputProvider.QWEN) "Fun-ASR" else strings.localWhisper) }, + text = { Text(if (provider == VoiceInputProvider.QWEN) "Fun-ASR" else strings.localModel) }, leadingIcon = { if (provider == config.provider) Icon(Icons.Default.Check, null) }, onClick = { - onUpdate { it.copy(provider = provider) } + onUpdate { + it.copy( + provider = provider, + language = if ( + provider == VoiceInputProvider.LOCAL_MODEL && + it.language !in localSpeechLanguages + ) "auto" else it.language, + ) + } providerMenu = false }, ) @@ -111,13 +121,13 @@ internal fun VoiceInputServiceSection( } if (showLocalModel) { LocalSpeechModelSettings( - model = config.localWhisperModel, + model = config.localSpeechModel, status = localModelStatus, supported = localRecognizer.supported, strings = strings, - onModelChange = { model -> onUpdate { it.copy(localWhisperModel = model) } }, - onDownload = { onDownloadLocalModel(config.localWhisperModel) }, - onCancel = { onCancelLocalModel(config.localWhisperModel) }, + onModelChange = { model -> onUpdate { it.copy(localSpeechModel = model) } }, + onDownload = { onDownloadLocalModel(config.localSpeechModel) }, + onCancel = { onCancelLocalModel(config.localSpeechModel) }, ) } if (config.provider == VoiceInputProvider.QWEN) { @@ -223,7 +233,10 @@ internal fun VoiceInputServiceSection( Icon(Icons.Default.ArrowDropDown, null) } DropdownMenu(languageMenu, { languageMenu = false }) { - listOf("auto", "zh", "ja", "en", "ko", "de", "fr", "ru").forEach { language -> + val languages = + if (config.provider == VoiceInputProvider.LOCAL_MODEL) localSpeechLanguages + else listOf("auto", "zh", "ja", "en", "ko", "de", "fr", "ru") + languages.forEach { language -> DropdownMenuItem( text = { Text(language) }, leadingIcon = { if (language == config.language) Icon(Icons.Default.Check, null) }, @@ -335,11 +348,11 @@ internal fun VoiceInputServiceSection( @Composable internal fun LocalSpeechModelSettings( - model: LocalWhisperModel, + model: LocalSpeechModel, status: LocalSpeechModelStatus, supported: Boolean, strings: LocaleStrings, - onModelChange: (LocalWhisperModel) -> Unit, + onModelChange: (LocalSpeechModel) -> Unit, onDownload: () -> Unit, onCancel: () -> Unit, ) { @@ -356,7 +369,7 @@ internal fun LocalSpeechModelSettings( Icon(Icons.Default.ArrowDropDown, null) } DropdownMenu(modelMenu, { modelMenu = false }) { - LocalWhisperModel.entries.forEach { option -> + LocalSpeechModel.entries.forEach { option -> DropdownMenuItem( text = { Text(option.displayLabel) }, leadingIcon = { if (option == model) Icon(Icons.Default.Check, null) }, @@ -369,6 +382,13 @@ internal fun LocalSpeechModelSettings( } } Text(strings.localModelHint, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + if (model == LocalSpeechModel.FUN_ASR_NANO_2512_INT8) { + Text( + strings.funAsrNanoHint, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.tertiary, + ) + } if (!supported) { Text(strings.localModelUnsupported, color = MaterialTheme.colorScheme.error) return@Column diff --git a/composeApp/src/commonMain/kotlin/com/vrcmc/app/ui/pages/ApiPage.kt b/composeApp/src/commonMain/kotlin/com/vrcmc/app/ui/pages/ApiPage.kt index e9abac5..972f4f9 100644 --- a/composeApp/src/commonMain/kotlin/com/vrcmc/app/ui/pages/ApiPage.kt +++ b/composeApp/src/commonMain/kotlin/com/vrcmc/app/ui/pages/ApiPage.kt @@ -19,8 +19,8 @@ import kotlinx.coroutines.launch fun ApiPage( state: AppState, strings: LocaleStrings, - onDownloadLocalModel: (LocalWhisperModel) -> Unit, - onCancelLocalModel: (LocalWhisperModel) -> Unit, + onDownloadLocalModel: (LocalSpeechModel) -> Unit, + onCancelLocalModel: (LocalSpeechModel) -> Unit, ) { val provider = state.provider val config = state.providerConfig diff --git a/composeApp/src/commonMain/kotlin/com/vrcmc/app/ui/pages/ChatPage.kt b/composeApp/src/commonMain/kotlin/com/vrcmc/app/ui/pages/ChatPage.kt index 1730ca2..9115dab 100644 --- a/composeApp/src/commonMain/kotlin/com/vrcmc/app/ui/pages/ChatPage.kt +++ b/composeApp/src/commonMain/kotlin/com/vrcmc/app/ui/pages/ChatPage.kt @@ -123,12 +123,12 @@ fun ChatPage( val voiceTypingHold = remember { VoiceTypingHold() } val streamingMerger = remember { StreamingTextMerger() } val audioRecorder = remember { audioRecorderFactory() } - val localSpeechStatusFlow = remember(state.voiceInputConfig.localWhisperModel) { - localSpeechRecognizer.status(state.voiceInputConfig.localWhisperModel) + val localSpeechStatusFlow = remember(state.voiceInputConfig.localSpeechModel) { + localSpeechRecognizer.status(state.voiceInputConfig.localSpeechModel) } val localSpeechStatus by localSpeechStatusFlow.collectAsState() val voiceServiceReady = state.voiceInputConfig.enabled && state.voiceInputConfig.hasServiceConfiguration() && - (state.voiceInputConfig.provider != VoiceInputProvider.LOCAL_WHISPER || localSpeechStatus == LocalSpeechModelStatus.Ready) + (state.voiceInputConfig.provider != VoiceInputProvider.LOCAL_MODEL || localSpeechStatus == LocalSpeechModelStatus.Ready) val scope = rememberCoroutineScope() val blockedSnackbar = remember { SnackbarHostState() } var blockedNotificationJob by remember { mutableStateOf(null) } @@ -285,7 +285,7 @@ fun ChatPage( }, onPartial = { wav -> scope.launch { - if (generation == voiceGeneration && config.provider != VoiceInputProvider.LOCAL_WHISPER) { + if (generation == voiceGeneration && config.provider != VoiceInputProvider.LOCAL_MODEL) { submitPartialRecognition(wav) } } diff --git a/composeApp/src/commonTest/kotlin/com/vrcmc/app/audio/VoiceInputTest.kt b/composeApp/src/commonTest/kotlin/com/vrcmc/app/audio/VoiceInputTest.kt index ccc733e..0b0dfa7 100644 --- a/composeApp/src/commonTest/kotlin/com/vrcmc/app/audio/VoiceInputTest.kt +++ b/composeApp/src/commonTest/kotlin/com/vrcmc/app/audio/VoiceInputTest.kt @@ -9,13 +9,18 @@ import kotlin.math.sin class VoiceInputTest { @Test - fun localProviderRoundTripsAndOldSettingsKeepQwen() { - val config = VoiceInputConfig(enabled = true, provider = VoiceInputProvider.LOCAL_WHISPER, - localWhisperModel = LocalWhisperModel.MEDIUM_Q5_0, - apiKey = "retained-secret", model = "my-qwen-model", region = "custom") + fun localProviderRoundTripsAndMigratesLegacyWhisperSettings() { + val config = VoiceInputConfig( + enabled = true, + provider = VoiceInputProvider.LOCAL_MODEL, + localSpeechModel = LocalSpeechModel.SENSE_VOICE_SMALL_INT8, + apiKey = "retained-secret", + model = "my-qwen-model", + region = "custom", + ) val json = StoredTranslationSettings(voiceInput = config).toJson() assertFalse(json.contains("retained-secret")) - assertTrue(json.contains("medium-q5_0")) + assertTrue(json.contains("sense-voice-small-int8")) assertEquals(config.copy(apiKey = ""), storedTranslationSettingsFromJson(json).voiceInput) assertEquals(VoiceInputProvider.QWEN, storedTranslationSettingsFromJson("""{"voiceInput":{"enabled":true}}""").voiceInput.provider) assertEquals(VoiceInputProvider.QWEN, storedTranslationSettingsFromJson("""{"voiceInput":{"provider":"unknown"}}""").voiceInput.provider) @@ -25,15 +30,21 @@ class VoiceInputTest { storedTranslationSettingsFromJson("""{"voiceInput":{"enabled":true}}""").voiceInput.vadMinRms, ) assertEquals( - LocalWhisperModel.SMALL_Q5_1, + LocalSpeechModel.SENSE_VOICE_SMALL_INT8, storedTranslationSettingsFromJson("""{"voiceInput":{"provider":"LOCAL_WHISPER"}}""") - .voiceInput.localWhisperModel, + .voiceInput.localSpeechModel, + ) + assertEquals( + VoiceInputProvider.LOCAL_MODEL, + storedTranslationSettingsFromJson( + """{"voiceInput":{"provider":"LOCAL_WHISPER","localWhisperModel":"medium-q5_0"}}""", + ).voiceInput.provider, ) assertEquals( - LocalWhisperModel.SMALL_Q5_1, + LocalSpeechModel.SENSE_VOICE_SMALL_INT8, storedTranslationSettingsFromJson( """{"voiceInput":{"provider":"LOCAL_WHISPER","localWhisperModel":"unknown"}}""", - ).voiceInput.localWhisperModel, + ).voiceInput.localSpeechModel, ) } diff --git a/composeApp/src/desktopMain/kotlin/com/vrcmc/app/audio/LocalSpeechRecognition.desktop.kt b/composeApp/src/desktopMain/kotlin/com/vrcmc/app/audio/LocalSpeechRecognition.desktop.kt index 10b2307..7d32468 100644 --- a/composeApp/src/desktopMain/kotlin/com/vrcmc/app/audio/LocalSpeechRecognition.desktop.kt +++ b/composeApp/src/desktopMain/kotlin/com/vrcmc/app/audio/LocalSpeechRecognition.desktop.kt @@ -1,287 +1,31 @@ package com.vrcmc.app import com.sun.jna.Platform -import com.sun.jna.platform.win32.Kernel32 -import io.github.givimad.whisperjni.WhisperContextParams -import io.github.givimad.whisperjni.WhisperFullParams -import io.github.givimad.whisperjni.WhisperJNI -import io.github.givimad.whisperjni.WhisperSamplingStrategy -import java.io.ByteArrayInputStream import java.nio.file.Path -import javax.sound.sampled.AudioFormat -import javax.sound.sampled.AudioSystem -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.NonCancellable -import kotlinx.coroutines.currentCoroutineContext -import kotlinx.coroutines.ensureActive -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock -import kotlinx.coroutines.withContext internal actual val localSpeechRecognizer: LocalSpeechRecognizer by lazy { - DesktopLocalSpeechRecognizer( - stores = LocalWhisperModel.entries.associateWith { model -> - LocalWhisperModelStore( - path = localWhisperModelPath(model), - expectedSize = model.modelSize(), - expectedHash = model.modelSha256(), - ) + JvmLocalSpeechRecognizer( + stores = LocalSpeechModel.entries.associateWith { model -> + model.createStore(desktopLocalSpeechModelPath(model)) }, + supported = localSpeechSupported(), ) } -private fun localWhisperModelPath(model: LocalWhisperModel): Path { - val overrideProperty = when (model) { - LocalWhisperModel.SMALL_Q5_1 -> "vrcmc.whisperModel.path" - LocalWhisperModel.MEDIUM_Q5_0 -> "vrcmc.whisperMediumModel.path" +private fun desktopLocalSpeechModelPath(model: LocalSpeechModel): Path { + val property = when (model) { + LocalSpeechModel.SENSE_VOICE_SMALL_INT8 -> "vrcmc.senseVoiceModel.path" + LocalSpeechModel.FUN_ASR_NANO_2512_INT8 -> "vrcmc.funAsrNanoModel.path" } - System.getProperty(overrideProperty)?.takeIf(String::isNotBlank)?.let { return Path.of(it) } + System.getProperty(property)?.takeIf(String::isNotBlank)?.let { return Path.of(it) } val root = System.getenv("LOCALAPPDATA")?.takeIf(String::isNotBlank)?.let { Path.of(it, "VRCMC") } ?: Path.of(System.getProperty("user.home"), ".vrcmc") val directory = when (model) { - LocalWhisperModel.SMALL_Q5_1 -> "whisper-small" - LocalWhisperModel.MEDIUM_Q5_0 -> "whisper-medium" + LocalSpeechModel.SENSE_VOICE_SMALL_INT8 -> "sense-voice-small" + LocalSpeechModel.FUN_ASR_NANO_2512_INT8 -> "fun-asr-nano-2512" } return root.resolve("models").resolve(directory).resolve(model.modelFileName()) } -internal fun localWhisperSupported(): Boolean = - Platform.isWindows() && Platform.is64Bit() && !Platform.isARM() && - // The bundled Windows JNI binary requires AVX2; reject unsupported CPUs before loading it. - Kernel32.INSTANCE.IsProcessorFeaturePresent(40) - -internal interface LocalWhisperEngine : AutoCloseable { - fun transcribe(samples: FloatArray, language: String): String -} - -internal class DesktopLocalSpeechRecognizer( - private val stores: Map, - override val supported: Boolean = localWhisperSupported(), - private val download: suspend ( - LocalWhisperModel, - LocalWhisperModelStore, - (Long, Long) -> Unit, - ) -> Unit = ::downloadWhisperModel, - private val createEngine: (Path) -> LocalWhisperEngine = ::WhisperJniEngine, -) : LocalSpeechRecognizer { - internal constructor( - store: LocalWhisperModelStore, - supported: Boolean = localWhisperSupported(), - download: suspend (LocalWhisperModelStore, (Long, Long) -> Unit) -> Unit = { cache, progress -> - downloadWhisperModel(LocalWhisperModel.SMALL_Q5_1, cache, progress) - }, - createEngine: (Path) -> LocalWhisperEngine = ::WhisperJniEngine, - ) : this( - stores = mapOf(LocalWhisperModel.SMALL_Q5_1 to store), - supported = supported, - download = { _, cache, progress -> download(cache, progress) }, - createEngine = createEngine, - ) - - // Loading, inference and disposal share a lock: microphone and system audio may overlap. - private val mutex = Mutex() - private val downloadMutexes = LocalWhisperModel.entries.associateWith { Mutex() } - private val statuses = LocalWhisperModel.entries.associateWith { - MutableStateFlow(LocalSpeechModelStatus.Missing) - } - private var engine: LocalWhisperEngine? = null - private var loadedModel: LocalWhisperModel? = null - - override fun status(model: LocalWhisperModel) = statuses.getValue(model).asStateFlow() - - override suspend fun downloadModel(model: LocalWhisperModel): Boolean = withContext(Dispatchers.IO) { - if (!supported) return@withContext false - val store = stores[model] ?: return@withContext false - val downloadMutex = downloadMutexes.getValue(model) - if (!downloadMutex.tryLock()) return@withContext false - val modelStatus = statuses.getValue(model) - try { - val alreadyLoaded = mutex.withLock { - (engine != null && loadedModel == model).also { loaded -> - if (!loaded) { - modelStatus.value = LocalSpeechModelStatus.Downloading(0, store.expectedSize) - } - } - } - if (alreadyLoaded) return@withContext true - if (store.isValid()) { - mutex.withLock { modelStatus.value = cachedStatus(model) } - return@withContext true - } - // Network IO never holds the inference lock; service changes may release the engine. - download(model, store) { received, total -> - modelStatus.value = LocalSpeechModelStatus.Downloading(received, total) - } - currentCoroutineContext().ensureActive() - mutex.withLock { modelStatus.value = cachedStatus(model) } - true - } catch (error: CancellationException) { - withContext(NonCancellable) { - val valid = store.isValid() - mutex.withLock { - modelStatus.value = when { - engine != null && loadedModel == model -> LocalSpeechModelStatus.Ready - valid -> LocalSpeechModelStatus.Downloaded - else -> LocalSpeechModelStatus.Missing - } - } - } - throw error - } catch (error: Exception) { - mutex.withLock { - modelStatus.value = LocalSpeechModelStatus.Failed(error.message?.take(300).orEmpty()) - } - false - } finally { - downloadMutex.unlock() - } - } - - override suspend fun prepare(model: LocalWhisperModel): Boolean = withContext(Dispatchers.IO) { - mutex.withLock { - if (!supported) return@withLock false - val modelStatus = statuses.getValue(model) - if ( - engine != null && loadedModel == model && - modelStatus.value == LocalSpeechModelStatus.Ready - ) return@withLock true - if (modelStatus.value is LocalSpeechModelStatus.Downloading) return@withLock false - if (engine != null) closeEngine() - val store = stores[model] - if (store == null) { - modelStatus.value = LocalSpeechModelStatus.Missing - return@withLock false - } - modelStatus.value = LocalSpeechModelStatus.Preparing - var cached = false - try { - if (!store.isValid()) { - modelStatus.value = LocalSpeechModelStatus.Missing - return@withLock false - } - cached = true - currentCoroutineContext().ensureActive() - modelStatus.value = LocalSpeechModelStatus.Preparing - engine = createEngine(store.path) - loadedModel = model - currentCoroutineContext().ensureActive() - modelStatus.value = LocalSpeechModelStatus.Ready - true - } catch (error: CancellationException) { - closeEngine() - modelStatus.value = if (cached) LocalSpeechModelStatus.Downloaded else LocalSpeechModelStatus.Missing - throw error - } catch (error: Exception) { - preparationFailed(model, error) - } catch (error: LinkageError) { - preparationFailed(model, error) - } - } - } - - private fun preparationFailed(model: LocalWhisperModel, error: Throwable): Boolean { - closeEngine() - statuses.getValue(model).value = LocalSpeechModelStatus.Failed(error.message?.take(300).orEmpty()) - return false - } - - override suspend fun transcribe( - model: LocalWhisperModel, - wav: ByteArray, - language: String, - ): VoiceTranscriptionResult = - withContext(Dispatchers.IO) { - mutex.withLock { - if (!supported) return@withLock VoiceTranscriptionResult.Failure(reason = VoiceTranscriptionFailureReason.LOCAL_UNSUPPORTED) - val loaded = engine.takeIf { - loadedModel == model && statuses.getValue(model).value == LocalSpeechModelStatus.Ready - } - ?: return@withLock VoiceTranscriptionResult.Failure(reason = VoiceTranscriptionFailureReason.LOCAL_MODEL_NOT_READY) - if (wav.size <= 44) return@withLock VoiceTranscriptionResult.Failure(reason = VoiceTranscriptionFailureReason.NO_AUDIO) - try { - val samples = whisperPcmSamples(wav) - currentCoroutineContext().ensureActive() - val text = loaded.transcribe(samples, language).trim() - // JNI inference is synchronous. Cancelled recordings must never publish stale text. - currentCoroutineContext().ensureActive() - if (text.isBlank()) VoiceTranscriptionResult.Failure(reason = VoiceTranscriptionFailureReason.NO_AUDIO) - else VoiceTranscriptionResult.Success(text) - } catch (error: CancellationException) { - throw error - } catch (error: Exception) { - VoiceTranscriptionResult.Failure(error.message.orEmpty(), VoiceTranscriptionFailureReason.LOCAL_RECOGNITION_FAILED) - } catch (error: LinkageError) { - VoiceTranscriptionResult.Failure(error.message.orEmpty(), VoiceTranscriptionFailureReason.LOCAL_RECOGNITION_FAILED) - } - } - } - - override suspend fun release() = withContext(Dispatchers.IO) { - mutex.withLock { - if (engine != null) closeEngine() - } - } - - private fun cachedStatus(model: LocalWhisperModel): LocalSpeechModelStatus = - if (engine != null && loadedModel == model) LocalSpeechModelStatus.Ready - else LocalSpeechModelStatus.Downloaded - - private fun closeEngine() { - val previous = engine - val previousModel = loadedModel - engine = null - loadedModel = null - if (previousModel != null && statuses.getValue(previousModel).value == LocalSpeechModelStatus.Ready) { - statuses.getValue(previousModel).value = LocalSpeechModelStatus.Downloaded - } - previous?.close() - } -} - -private class WhisperJniEngine(model: Path) : LocalWhisperEngine { - private val whisper = WhisperJNI().also { - WhisperJNI.loadLibrary() - WhisperJNI.setLibraryLogger(null) - } - private val context = checkNotNull(whisper.init(model, WhisperContextParams().apply { useGPU = false })) { - "Could not load local Whisper model" - } - - override fun transcribe(samples: FloatArray, language: String): String { - val params = WhisperFullParams(WhisperSamplingStrategy.GREEDY).apply { - nThreads = Runtime.getRuntime().availableProcessors().let { (it / 2).coerceIn(1, 6) } - this.language = language.takeIf { it.isNotBlank() && it != "auto" } ?: "auto" - if (language == "zh") initialPrompt = "以下是普通话的简体中文转写。" - // The encoder otherwise pads even a short utterance to 30 seconds. Keep two - // seconds of padding and at least 15.36 seconds of context for short clips. - audioCtx = (((samples.size / 320 + 100 + 127) / 128) * 128).coerceIn(768, 1500) - translate = false - noContext = true - noTimestamps = true - printProgress = false - printRealtime = false - printTimestamps = false - suppressNonSpeechTokens = true - } - check(whisper.full(context, params, samples, samples.size) == 0) { "Whisper transcription failed" } - return (0 until whisper.fullNSegments(context)).joinToString("") { whisper.fullGetSegmentText(context, it) } - } - - override fun close() = context.close() -} - -internal fun whisperPcmSamples(wav: ByteArray): FloatArray { - val target = AudioFormat(16_000f, 16, 1, true, false) - val pcm = AudioSystem.getAudioInputStream(ByteArrayInputStream(wav)).use { source -> - AudioSystem.getAudioInputStream(target, source).use { it.readBytes() } - } - require(pcm.isNotEmpty() && pcm.size % 2 == 0) { "Invalid PCM audio" } - return FloatArray(pcm.size / 2) { index -> - val low = pcm[index * 2].toInt() and 0xff - val high = pcm[index * 2 + 1].toInt() - ((high shl 8) or low) / 32768f - } -} +internal fun localSpeechSupported(): Boolean = + Platform.isWindows() && Platform.is64Bit() && !Platform.isARM() diff --git a/composeApp/src/desktopMain/kotlin/com/vrcmc/app/audio/LocalWhisperModelStore.kt b/composeApp/src/desktopMain/kotlin/com/vrcmc/app/audio/LocalWhisperModelStore.kt deleted file mode 100644 index 05f4be7..0000000 --- a/composeApp/src/desktopMain/kotlin/com/vrcmc/app/audio/LocalWhisperModelStore.kt +++ /dev/null @@ -1,137 +0,0 @@ -package com.vrcmc.app - -import io.ktor.client.plugins.HttpTimeout -import io.ktor.client.request.prepareGet -import io.ktor.client.statement.bodyAsChannel -import io.ktor.http.isSuccess -import io.ktor.utils.io.ByteReadChannel -import io.ktor.utils.io.readAvailable -import java.nio.file.AtomicMoveNotSupportedException -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.StandardCopyOption -import java.security.MessageDigest -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.currentCoroutineContext -import kotlinx.coroutines.ensureActive - -private const val whisperModelRevision = "5359861c739e955e79d9a303bcbc70fb988958b1" - -private data class LocalWhisperModelArtifact( - val fileName: String, - val size: Long, - val sha256: String, -) - -private fun LocalWhisperModel.artifact(): LocalWhisperModelArtifact = when (this) { - LocalWhisperModel.SMALL_Q5_1 -> LocalWhisperModelArtifact( - fileName = "ggml-small-q5_1.bin", - size = 190_085_487L, - sha256 = "ae85e4a935d7a567bd102fe55afc16bb595bdb618e11b2fc7591bc08120411bb", - ) - LocalWhisperModel.MEDIUM_Q5_0 -> LocalWhisperModelArtifact( - fileName = "ggml-medium-q5_0.bin", - size = 539_212_467L, - sha256 = "19fea4b380c3a618ec4723c3eef2eb785ffba0d0538cf43f8f235e7b3b34220f", - ) -} - -internal fun LocalWhisperModel.modelFileName(): String = artifact().fileName -internal fun LocalWhisperModel.modelSize(): Long = artifact().size -internal fun LocalWhisperModel.modelSha256(): String = artifact().sha256 - -// Call on Dispatchers.IO. A failed or cancelled download must never replace a valid model. -internal class LocalWhisperModelStore( - val path: Path, - internal val expectedSize: Long = LocalWhisperModel.SMALL_Q5_1.modelSize(), - private val expectedHash: String = LocalWhisperModel.SMALL_Q5_1.modelSha256(), -) { - suspend fun isValid(): Boolean { - if (!Files.isRegularFile(path) || Files.size(path) != expectedSize) return false - val digest = MessageDigest.getInstance("SHA-256") - Files.newInputStream(path).use { input -> - val buffer = ByteArray(64 * 1024) - while (true) { - currentCoroutineContext().ensureActive() - val count = input.read(buffer) - if (count < 0) break - digest.update(buffer, 0, count) - } - } - return digest.digest().toHexString() == expectedHash - } - - suspend fun install(channel: ByteReadChannel, onProgress: (Long, Long) -> Unit) { - Files.createDirectories(path.toAbsolutePath().parent) - val temporary = Files.createTempFile(path.toAbsolutePath().parent, "whisper-", ".part") - try { - val digest = MessageDigest.getInstance("SHA-256") - var received = 0L - var reported = 0L - onProgress(0, expectedSize) - Files.newOutputStream(temporary).use { output -> - val buffer = ByteArray(64 * 1024) - while (true) { - currentCoroutineContext().ensureActive() - val count = channel.readAvailable(buffer, 0, buffer.size) - if (count < 0) break - if (count == 0) continue - received += count - check(received <= expectedSize) { "Model exceeds expected size" } - output.write(buffer, 0, count) - digest.update(buffer, 0, count) - if (received - reported >= 256 * 1024 || received == expectedSize) { - onProgress(received, expectedSize) - reported = received - } - } - } - check(received == expectedSize) { "Incomplete model download: $received / $expectedSize bytes" } - check(digest.digest().toHexString() == expectedHash) { "Model checksum mismatch" } - currentCoroutineContext().ensureActive() - try { - Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) - } catch (_: AtomicMoveNotSupportedException) { - Files.move(temporary, path, StandardCopyOption.REPLACE_EXISTING) - } - } finally { - Files.deleteIfExists(temporary) - } - } -} - -internal suspend fun downloadWhisperModel( - model: LocalWhisperModel, - store: LocalWhisperModelStore, - onProgress: (Long, Long) -> Unit, -) { - val client = createVrcmcHttpClient { - install(HttpTimeout) { - connectTimeoutMillis = 15_000 - socketTimeoutMillis = 60_000 - requestTimeoutMillis = 1_200_000 - } - } - try { - var lastFailure: Exception? = null - // Both sources serve the same pinned file; SHA-256 is checked before it can be loaded. - for (host in listOf("huggingface.co", "hf-mirror.com")) { - try { - client.prepareGet( - "https://$host/ggerganov/whisper.cpp/resolve/$whisperModelRevision/${model.modelFileName()}", - ).execute { response -> - check(response.status.isSuccess()) { "Model server returned HTTP ${response.status.value}" } - store.install(response.bodyAsChannel(), onProgress) - } - return - } catch (error: CancellationException) { - throw error - } catch (error: Exception) { - lastFailure = error - } - } - throw checkNotNull(lastFailure) - } finally { - client.close() - } -} diff --git a/composeApp/src/desktopMain/kotlin/com/vrcmc/app/audio/SystemAudioListener.desktop.kt b/composeApp/src/desktopMain/kotlin/com/vrcmc/app/audio/SystemAudioListener.desktop.kt index 0181215..e61873c 100644 --- a/composeApp/src/desktopMain/kotlin/com/vrcmc/app/audio/SystemAudioListener.desktop.kt +++ b/composeApp/src/desktopMain/kotlin/com/vrcmc/app/audio/SystemAudioListener.desktop.kt @@ -79,11 +79,11 @@ internal fun SystemAudioSubtitleWindow( val config = languageConfig.normalized() // Appearance changes must not cancel capture or clear completed captions. val listeningSettings = settings.withLanguages(config) - val localModelStatusFlow = remember(settings.voice.localWhisperModel) { - localSpeechRecognizer.status(settings.voice.localWhisperModel) + val localModelStatusFlow = remember(settings.voice.localSpeechModel) { + localSpeechRecognizer.status(settings.voice.localSpeechModel) } val localModelStatus by localModelStatusFlow.collectAsState() - val localModelReady = settings.voice.provider != VoiceInputProvider.LOCAL_WHISPER || + val localModelReady = settings.voice.provider != VoiceInputProvider.LOCAL_MODEL || localModelStatus == LocalSpeechModelStatus.Ready val windowState = rememberWindowState(width = 360.dp, height = 480.dp, position = WindowPosition(24.dp, 24.dp)) var showSettings by remember { mutableStateOf(false) } diff --git a/composeApp/src/desktopMain/resources/local-asr/README.md b/composeApp/src/desktopMain/resources/local-asr/README.md new file mode 100644 index 0000000..221359a --- /dev/null +++ b/composeApp/src/desktopMain/resources/local-asr/README.md @@ -0,0 +1,15 @@ +# Local speech recognition + +Local models are downloaded only after the user clicks Download model; they are not bundled in the application. Downloads continue across page and provider changes and when voice input is disabled. Only Cancel download explicitly cancels the task. Local inference is available on Windows x64. + +- Model: SenseVoice Small INT8, Chinese, Cantonese, English, Japanese, and Korean, subject to the [FunASR model license](https://github.com/modelscope/FunASR#license). +- Model source: https://huggingface.co/csukuangfj/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17/tree/2365baeacb507f821a0c8120fcee3d484dba7a07 +- `model.int8.onnx`: 239233841 bytes, SHA-256 `c71f0ce00bec95b07744e116345e33d8cbbe08cef896382cf907bf4b51a2cd51`. +- `tokens.txt`: 315894 bytes, SHA-256 `f449eb28dc567533d7fa59be34e2abca8784f771850c78a47fb731a31429a1dc`. +- Model: Fun-ASR-Nano 2512 INT8, with stronger dialect, accent, far-field, and noisy-speech recognition, subject to the FunASR model license. +- Model source: https://huggingface.co/csukuangfj/sherpa-onnx-sense-voice-funasr-nano-int8-2025-12-17/tree/ebb95fbda2a034d9a8f3b2d2cba32c104b60bed3 +- `fun-asr-nano-2512/model.int8.onnx`: 263531902 bytes, SHA-256 `9dc6e72aa8bc6f5966cf2857a0ce3a425b1d72e91500e147d66329f407c017a1`. +- `fun-asr-nano-2512/tokens.txt`: 939815 bytes, SHA-256 `2db4bb25d046e8849e336c9465e248e1694914d996c58c71bdeca18cfb722992`. +- Runtime: `com.microsoft.onnxruntime:onnxruntime:1.20.0` on Desktop. Feature extraction, LFR, normalization, and CTC decoding run locally. + +The application checks both file sizes and SHA-256 digests before loading the model, including files received from the HF Mirror fallback. No cloud recognition fallback is used. diff --git a/composeApp/src/desktopMain/resources/whisper/LICENSE.whisper b/composeApp/src/desktopMain/resources/whisper/LICENSE.whisper deleted file mode 100644 index d255525..0000000 --- a/composeApp/src/desktopMain/resources/whisper/LICENSE.whisper +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2022 OpenAI - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/composeApp/src/desktopMain/resources/whisper/LICENSE.whisper-cpp b/composeApp/src/desktopMain/resources/whisper/LICENSE.whisper-cpp deleted file mode 100644 index acb96ce..0000000 --- a/composeApp/src/desktopMain/resources/whisper/LICENSE.whisper-cpp +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2023-2024 The ggml authors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/composeApp/src/desktopMain/resources/whisper/LICENSE.whisper-jni b/composeApp/src/desktopMain/resources/whisper/LICENSE.whisper-jni deleted file mode 100644 index d645695..0000000 --- a/composeApp/src/desktopMain/resources/whisper/LICENSE.whisper-jni +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/composeApp/src/desktopMain/resources/whisper/README.md b/composeApp/src/desktopMain/resources/whisper/README.md deleted file mode 100644 index df0e6c1..0000000 --- a/composeApp/src/desktopMain/resources/whisper/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Local speech recognition - -The model is downloaded only after the user clicks Download model; it is not bundled in the application. Downloads continue across page and provider changes and when voice input is disabled. Only Cancel download explicitly cancels the task. - -- Models: OpenAI Whisper Small and Medium, multilingual, MIT license (`LICENSE.whisper`). -- GGML model source: https://huggingface.co/ggerganov/whisper.cpp/tree/5359861c739e955e79d9a303bcbc70fb988958b1 -- Small Q5_1: `ggml-small-q5_1.bin`, 190085487 bytes, SHA-256 `ae85e4a935d7a567bd102fe55afc16bb595bdb618e11b2fc7591bc08120411bb`. -- Medium Q5_0: `ggml-medium-q5_0.bin`, 539212467 bytes, SHA-256 `19fea4b380c3a618ec4723c3eef2eb785ffba0d0538cf43f8f235e7b3b34220f`. -- Runtime: `io.github.givimad:whisper-jni:1.7.1`, Apache-2.0 (`LICENSE.whisper-jni`), wrapping whisper.cpp (MIT, `LICENSE.whisper-cpp`). -- Windows native binaries require x64 and AVX2. Inference uses the CPU with up to six threads. - -The application checks the pinned file size and digest before loading it, including files received from the HF Mirror fallback. No cloud recognition fallback is used. diff --git a/composeApp/src/desktopTest/kotlin/com/vrcmc/app/audio/FunAsrNanoRecognitionTest.kt b/composeApp/src/desktopTest/kotlin/com/vrcmc/app/audio/FunAsrNanoRecognitionTest.kt new file mode 100644 index 0000000..a0463ff --- /dev/null +++ b/composeApp/src/desktopTest/kotlin/com/vrcmc/app/audio/FunAsrNanoRecognitionTest.kt @@ -0,0 +1,31 @@ +package com.vrcmc.app + +import java.nio.file.Files +import java.nio.file.Path +import kotlin.test.Test +import kotlin.test.assertIs +import kotlin.test.assertTrue +import kotlinx.coroutines.runBlocking + +class FunAsrNanoRecognitionTest { + @Test + fun recognizesOfficialChineseFixture() = runBlocking { + org.junit.Assume.assumeTrue(System.getenv("VRCMC_FUN_ASR_INTEGRATION_TEST") == "1") + val model = LocalSpeechModel.FUN_ASR_NANO_2512_INT8 + val root = Path.of("..", "build", "funasr-test") + val store = model.createStore(root.resolve(model.modelFileName())) + assertTrue(store.isComplete()) + val recognizer = JvmLocalSpeechRecognizer(mapOf(model to store), supported = true) + try { + assertTrue(recognizer.prepare(model), recognizer.status(model).value.toString()) + val wav = Files.readAllBytes(root.resolve("zh.wav")) + val result = assertIs( + recognizer.transcribe(model, wav, "auto"), + ) + println("Fun-ASR-Nano zh: ${result.text}") + assertTrue(result.text.isNotBlank()) + } finally { + recognizer.release() + } + } +} diff --git a/composeApp/src/desktopTest/kotlin/com/vrcmc/app/audio/LocalSpeechRecognitionTest.kt b/composeApp/src/desktopTest/kotlin/com/vrcmc/app/audio/LocalSpeechRecognitionTest.kt index 52af91d..abc16e8 100644 --- a/composeApp/src/desktopTest/kotlin/com/vrcmc/app/audio/LocalSpeechRecognitionTest.kt +++ b/composeApp/src/desktopTest/kotlin/com/vrcmc/app/audio/LocalSpeechRecognitionTest.kt @@ -3,7 +3,6 @@ package com.vrcmc.app import io.ktor.utils.io.ByteChannel import io.ktor.utils.io.ByteReadChannel import java.nio.file.Files -import java.nio.file.Path import java.security.MessageDigest import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit @@ -28,302 +27,248 @@ import org.junit.rules.TemporaryFolder class LocalSpeechRecognitionTest { @get:Rule val directory = TemporaryFolder() - private val small = LocalWhisperModel.SMALL_Q5_1 - private val medium = LocalWhisperModel.MEDIUM_Q5_0 - private val model = ByteArray(2048) { it.toByte() } + private val model = LocalSpeechModel.SENSE_VOICE_SMALL_INT8 + private val modelBytes = ByteArray(2048) { it.toByte() } + private val tokens = ByteArray(256) { (it * 3).toByte() } private val wav = pcm16ToWav(ByteArray(32_000) { if (it % 2 == 0) 0 else 16 }, 16_000) - private fun store(fileName: String = "ggml-small-q5_1.bin"): LocalWhisperModelStore = LocalWhisperModelStore( - directory.root.toPath().resolve(fileName), model.size.toLong(), - MessageDigest.getInstance("SHA-256").digest(model).toHexString(), + private fun store(): LocalSpeechModelStore = LocalSpeechModelStore( + path = directory.root.toPath().resolve("model.int8.onnx"), + expectedSize = modelBytes.size.toLong(), + expectedHash = sha256(modelBytes), + auxiliaryPath = directory.root.toPath().resolve("tokens.txt"), + expectedAuxiliarySize = tokens.size.toLong(), + expectedAuxiliaryHash = sha256(tokens), ) @Test - fun modelArtifactsMatchPinnedWhisperCppFiles() { - assertEquals("ggml-small-q5_1.bin", small.modelFileName()) - assertEquals(190_085_487L, small.modelSize()) + fun modelArtifactMatchesPinnedSenseVoiceFile() { + assertEquals("model.int8.onnx", model.modelFileName()) + assertEquals(239_233_841L, model.modelSize()) assertEquals( - "ae85e4a935d7a567bd102fe55afc16bb595bdb618e11b2fc7591bc08120411bb", - small.modelSha256(), + "c71f0ce00bec95b07744e116345e33d8cbbe08cef896382cf907bf4b51a2cd51", + model.modelSha256(), ) - assertEquals("ggml-medium-q5_0.bin", medium.modelFileName()) - assertEquals(539_212_467L, medium.modelSize()) + val funAsr = LocalSpeechModel.FUN_ASR_NANO_2512_INT8 + assertEquals("model.int8.onnx", funAsr.modelFileName()) + assertEquals(263_531_902L, funAsr.modelSize()) assertEquals( - "19fea4b380c3a618ec4723c3eef2eb785ffba0d0538cf43f8f235e7b3b34220f", - medium.modelSha256(), + "9dc6e72aa8bc6f5966cf2857a0ce3a425b1d72e91500e147d66329f407c017a1", + funAsr.modelSha256(), ) } @Test - fun verifiesCacheAndPreservesItAfterTruncatedOrCorruptDownloads() = runBlocking { - val store = store() - assertFalse(store.isValid()) - store.install(ByteReadChannel(model)) { _, _ -> } - assertTrue(store.isValid()) - for (bad in listOf(model.copyOf(20), ByteArray(model.size), model + byteArrayOf(0))) { - assertTrue(runCatching { store.install(ByteReadChannel(bad)) { _, _ -> } }.isFailure) - assertTrue(store.isValid()) + fun verifiesModelAndAuxiliaryCacheAndPreservesValidFiles() = runBlocking { + val cache = store() + assertFalse(cache.isComplete()) + cache.install(ByteReadChannel(modelBytes)) { _, _ -> } + assertFalse(cache.isComplete()) + cache.installAuxiliary(ByteReadChannel(tokens)) { _, _ -> } + assertTrue(cache.isComplete()) + + for (bad in listOf(modelBytes.copyOf(20), ByteArray(modelBytes.size), modelBytes + byteArrayOf(0))) { + assertTrue(runCatching { cache.install(ByteReadChannel(bad)) { _, _ -> } }.isFailure) + assertTrue(cache.isComplete()) } - Files.list(directory.root.toPath()).use { assertEquals(1, it.count()) } - Files.write(store.path, ByteArray(model.size)) - assertFalse(store.isValid()) + Files.delete(cache.auxiliaryPath) + assertFalse(cache.isComplete()) } @Test fun cancelledDownloadRemovesTemporaryFileAndCanRetry() = runBlocking { - val store = store() + val cache = store() val opened = CompletableDeferred() val channel = ByteChannel() - val job = launch { store.install(channel) { _, _ -> opened.complete(Unit) } } + val job = launch { cache.install(channel) { _, _ -> opened.complete(Unit) } } withTimeout(5_000) { opened.await() } job.cancelAndJoin() channel.cancel(null) - assertFalse(Files.exists(store.path)) - Files.list(directory.root.toPath()).use { assertEquals(0, it.count()) } - store.install(ByteReadChannel(model)) { _, _ -> } - assertTrue(store.isValid()) - } - - @Test - fun downloadsOnlyRequestedModelAndTracksStatusesIndependently() = runBlocking { - val smallStore = store() - val mediumStore = store("ggml-medium-q5_0.bin") - val downloads = mutableListOf() - val recognizer = DesktopLocalSpeechRecognizer( - stores = mapOf(small to smallStore, medium to mediumStore), - supported = true, - download = { selected, cache, progress -> - downloads += selected - cache.install(ByteReadChannel(model), progress) - }, - createEngine = { fakeEngine() }, - ) - - assertTrue(recognizer.downloadModel(medium)) - - assertEquals(listOf(medium), downloads) - assertEquals(LocalSpeechModelStatus.Missing, recognizer.status(small).value) - assertEquals(LocalSpeechModelStatus.Downloaded, recognizer.status(medium).value) - assertFalse(Files.exists(smallStore.path)) - assertTrue(mediumStore.isValid()) + assertFalse(Files.exists(cache.path)) + cache.install(ByteReadChannel(modelBytes)) { _, _ -> } + assertTrue(cache.isValid()) } @Test - fun switchingModelsClosesOldEngineAndUsesSelectedCache() = runBlocking { - val smallStore = store() - val mediumStore = store("ggml-medium-q5_0.bin") - smallStore.install(ByteReadChannel(model)) { _, _ -> } - mediumStore.install(ByteReadChannel(model)) { _, _ -> } - val loaded = mutableListOf() - val closed = mutableListOf() - val recognizer = DesktopLocalSpeechRecognizer( - stores = mapOf(small to smallStore, medium to mediumStore), - supported = true, - createEngine = { path -> - val name = path.fileName.toString() - loaded += name - object : LocalWhisperEngine { - override fun transcribe(samples: FloatArray, language: String) = name - override fun close() { closed += name } + fun preparationLoadsEngineAndTranscribes() = runBlocking { + val cache = store() + cache.install(ByteReadChannel(modelBytes)) { _, _ -> } + cache.installAuxiliary(ByteReadChannel(tokens)) { _, _ -> } + var loads = 0 + var closes = 0 + val recognizer = JvmLocalSpeechRecognizer(cache, supported = true, createEngine = { _, _ -> + loads++ + object : LocalSpeechEngine { + override fun transcribe(samples: FloatArray, language: String) = "$language: local speech" + override fun close() { + closes++ } - }, - ) + } + }) - assertTrue(recognizer.prepare(small)) + assertTrue(recognizer.prepare(model)) + assertEquals(LocalSpeechModelStatus.Ready, recognizer.status(model).value) assertEquals( - VoiceTranscriptionResult.Success("ggml-small-q5_1.bin"), - recognizer.transcribe(small, wav, "en"), + VoiceTranscriptionResult.Success("zh: local speech"), + recognizer.transcribe(model, wav, "zh"), ) + recognizer.release() + assertEquals(LocalSpeechModelStatus.Downloaded, recognizer.status(model).value) + assertEquals(1, loads) + assertEquals(1, closes) assertEquals( VoiceTranscriptionFailureReason.LOCAL_MODEL_NOT_READY, - assertIs(recognizer.transcribe(medium, wav, "en")).reason, - ) - - assertTrue(recognizer.prepare(medium)) - - assertEquals(listOf("ggml-small-q5_1.bin", "ggml-medium-q5_0.bin"), loaded) - assertEquals(listOf("ggml-small-q5_1.bin"), closed) - assertEquals(LocalSpeechModelStatus.Downloaded, recognizer.status(small).value) - assertEquals(LocalSpeechModelStatus.Ready, recognizer.status(medium).value) - assertEquals( - VoiceTranscriptionResult.Success("ggml-medium-q5_0.bin"), - recognizer.transcribe(medium, wav, "en"), + assertIs(recognizer.transcribe(model, wav, "zh")).reason, ) - recognizer.release() - assertEquals(listOf("ggml-small-q5_1.bin", "ggml-medium-q5_0.bin"), closed) } @Test - fun missingMediumNeverUsesLoadedSmallEngine() = runBlocking { - val smallStore = store() - smallStore.install(ByteReadChannel(model)) { _, _ -> } - var closes = 0 - val recognizer = DesktopLocalSpeechRecognizer( - stores = mapOf(small to smallStore, medium to store("ggml-medium-q5_0.bin")), + fun switchingModelsClosesThePreviousEngine() = runBlocking { + val sense = LocalSpeechModel.SENSE_VOICE_SMALL_INT8 + val funAsr = LocalSpeechModel.FUN_ASR_NANO_2512_INT8 + fun modelStore(name: String) = LocalSpeechModelStore( + path = directory.root.toPath().resolve(name).resolve("model.int8.onnx"), + expectedSize = modelBytes.size.toLong(), + expectedHash = sha256(modelBytes), + auxiliaryPath = directory.root.toPath().resolve(name).resolve("tokens.txt"), + expectedAuxiliarySize = tokens.size.toLong(), + expectedAuxiliaryHash = sha256(tokens), + ) + val senseStore = modelStore("sense") + val funStore = modelStore("fun") + for (store in listOf(senseStore, funStore)) { + store.install(ByteReadChannel(modelBytes)) { _, _ -> } + store.installAuxiliary(ByteReadChannel(tokens)) { _, _ -> } + } + val closed = mutableListOf() + val recognizer = JvmLocalSpeechRecognizer( + stores = mapOf(sense to senseStore, funAsr to funStore), supported = true, - createEngine = { - object : LocalWhisperEngine { - override fun transcribe(samples: FloatArray, language: String) = "small result" - override fun close() { closes++ } + createEngine = { selected, _ -> + object : LocalSpeechEngine { + override fun transcribe(samples: FloatArray, language: String) = selected.serializedName + override fun close() { + closed += selected + } } }, ) - assertTrue(recognizer.prepare(small)) - - assertFalse(recognizer.prepare(medium)) - assertEquals(1, closes) - assertEquals(LocalSpeechModelStatus.Downloaded, recognizer.status(small).value) - assertEquals(LocalSpeechModelStatus.Missing, recognizer.status(medium).value) + assertTrue(recognizer.prepare(sense)) assertEquals( - VoiceTranscriptionFailureReason.LOCAL_MODEL_NOT_READY, - assertIs(recognizer.transcribe(medium, wav, "en")).reason, + VoiceTranscriptionResult.Success(sense.serializedName), + recognizer.transcribe(sense, wav, "zh"), + ) + assertTrue(recognizer.prepare(funAsr)) + assertEquals(listOf(sense), closed) + assertEquals( + VoiceTranscriptionResult.Success(funAsr.serializedName), + recognizer.transcribe(funAsr, wav, "zh"), ) + recognizer.release() + assertEquals(listOf(sense, funAsr), closed) } @Test - fun preparationNeverDownloadsAndExplicitRetryReusesVerifiedModel() = runBlocking { - val store = store() + fun preparationNeverDownloadsAndExplicitRetryReusesVerifiedFiles() = runBlocking { + val cache = store() var downloads = 0 - var loads = 0 - var closes = 0 - val recognizer = DesktopLocalSpeechRecognizer(store, supported = true, - download = { cache, progress -> + val recognizer = JvmLocalSpeechRecognizer( + cache, + supported = true, + download = { target, progress -> downloads++ if (downloads == 1) error("Simulated connection failure") - cache.install(ByteReadChannel(model), progress) + target.install(ByteReadChannel(modelBytes), progress) + target.installAuxiliary(ByteReadChannel(tokens)) { _, _ -> } }, - createEngine = { - loads++ - object : LocalWhisperEngine { - override fun transcribe(samples: FloatArray, language: String) = "$language: local speech" - override fun close() { closes++ } - } - }) - assertFalse(recognizer.prepare(small)) - assertEquals(LocalSpeechModelStatus.Missing, recognizer.status(small).value) - assertEquals(0, downloads) - assertFalse(recognizer.downloadModel(small)) - assertIs(recognizer.status(small).value) - assertTrue(recognizer.downloadModel(small)) - assertEquals(LocalSpeechModelStatus.Downloaded, recognizer.status(small).value) - assertEquals(0, loads) - assertTrue(recognizer.prepare(small)) - assertEquals(LocalSpeechModelStatus.Ready, recognizer.status(small).value) - assertTrue(recognizer.prepare(small)) - assertEquals(1, loads) - assertEquals( - VoiceTranscriptionResult.Success("ja: local speech"), - recognizer.transcribe(small, wav, "ja"), + createEngine = { _, _ -> fakeEngine() }, ) - recognizer.release() - assertEquals(LocalSpeechModelStatus.Downloaded, recognizer.status(small).value) - assertEquals(1, closes) - assertEquals(VoiceTranscriptionFailureReason.LOCAL_MODEL_NOT_READY, - assertIs(recognizer.transcribe(small, wav, "ja")).reason) - assertTrue(recognizer.prepare(small)) - assertEquals(2, downloads) - assertEquals(2, loads) - recognizer.release() - assertEquals(2, closes) - } - - @Test - fun cancelledDownloadLeavesMissingStatusAndRequiresManualRetry() = runBlocking { - val started = CompletableDeferred() - var attempt = 0 - val recognizer = DesktopLocalSpeechRecognizer(store(), supported = true, - download = { cache, progress -> - if (++attempt == 1) { - started.complete(Unit) - kotlinx.coroutines.awaitCancellation() - } - cache.install(ByteReadChannel(model), progress) - }, createEngine = { fakeEngine() }) - val preparation = launch { recognizer.downloadModel(small) } - withTimeout(5_000) { started.await() } - preparation.cancelAndJoin() - assertEquals(LocalSpeechModelStatus.Missing, recognizer.status(small).value) - assertFalse(recognizer.prepare(small)) - assertEquals(1, attempt) - assertTrue(recognizer.downloadModel(small)) - assertTrue(recognizer.prepare(small)) - recognizer.release() + assertFalse(recognizer.prepare(model)) + assertEquals(LocalSpeechModelStatus.Missing, recognizer.status(model).value) + assertEquals(0, downloads) + assertFalse(recognizer.downloadModel(model)) + assertIs(recognizer.status(model).value) + assertTrue(recognizer.downloadModel(model)) + assertEquals(LocalSpeechModelStatus.Downloaded, recognizer.status(model).value) + assertTrue(recognizer.prepare(model)) + assertEquals(LocalSpeechModelStatus.Ready, recognizer.status(model).value) } @Test - fun unsupportedPlatformDoesNotDownloadOrLoadNativeCode() = runBlocking { - val recognizer = DesktopLocalSpeechRecognizer(store(), supported = false, - download = { _, _ -> error("Must not download") }, createEngine = { error("Must not load JNI") }) - assertFalse(recognizer.prepare(small)) - assertFalse(recognizer.downloadModel(small)) - assertEquals(VoiceTranscriptionFailureReason.LOCAL_UNSUPPORTED, - assertIs(recognizer.transcribe(small, wav, "auto")).reason) + fun unsupportedPlatformDoesNotLoadOrDownload() = runBlocking { + val recognizer = JvmLocalSpeechRecognizer( + store(), + supported = false, + download = { _, _ -> error("Must not download") }, + createEngine = { _, _ -> error("Must not load ONNX Runtime") }, + ) + assertFalse(recognizer.prepare(model)) + assertFalse(recognizer.downloadModel(model)) + assertEquals( + VoiceTranscriptionFailureReason.LOCAL_UNSUPPORTED, + assertIs( + recognizer.transcribe(model, wav, "auto"), + ).reason, + ) } @Test - fun applicationDownloadSurvivesServiceChangesUntilExplicitCancellation() = runBlocking { + fun applicationDownloadSurvivesServiceChangesUntilExplicitCancellation(): Unit = runBlocking { val cache = store() val started = CompletableDeferred() val stream = ByteChannel() val preparations = Channel(Channel.UNLIMITED) val releases = Channel(Channel.UNLIMITED) var downloads = 0 - var loads = 0 - val recognizer = DesktopLocalSpeechRecognizer(cache, supported = true, - download = { store, progress -> + val recognizer = JvmLocalSpeechRecognizer( + cache, + supported = true, + download = { target, progress -> if (++downloads == 1) { - store.install(stream) { received, total -> + target.install(stream) { received, total -> progress(received, total) started.complete(Unit) } - } else store.install(ByteReadChannel(model), progress) - }, createEngine = { loads++; fakeEngine() }) + } else { + target.install(ByteReadChannel(modelBytes), progress) + target.installAuxiliary(ByteReadChannel(tokens)) { _, _ -> } + } + }, + createEngine = { _, _ -> fakeEngine() }, + ) val observed = object : LocalSpeechRecognizer by recognizer { - override suspend fun prepare(model: LocalWhisperModel) = + override suspend fun prepare(model: LocalSpeechModel) = recognizer.prepare(model).also { preparations.send(Unit) } - override suspend fun release() { recognizer.release(); releases.send(Unit) } + + override suspend fun release() { + recognizer.release() + releases.send(Unit) + } } val lifetime = Job() val controller = LocalSpeechModelController(CoroutineScope(coroutineContext + lifetime), observed) - val local = VoiceInputConfig(enabled = true, provider = VoiceInputProvider.LOCAL_WHISPER) + val local = VoiceInputConfig(enabled = true, provider = VoiceInputProvider.LOCAL_MODEL) try { - withTimeout(5_000) { + withTimeout(10_000) { controller.updateConfig(local) preparations.receive() - assertEquals(0, downloads) - assertEquals(LocalSpeechModelStatus.Missing, recognizer.status(small).value) - controller.downloadModel(small) - controller.downloadModel(small) + controller.downloadModel(model) + controller.downloadModel(model) started.await() - assertEquals(1, downloads) - controller.updateConfig(local.copy(provider = VoiceInputProvider.QWEN)) releases.receive() - assertIs(recognizer.status(small).value) controller.updateConfig(local) preparations.receive() - assertIs(recognizer.status(small).value) - controller.updateConfig(local.copy(enabled = false)) - releases.receive() - assertIs(recognizer.status(small).value) + controller.cancelDownload(model) + recognizer.status(model).first { it == LocalSpeechModelStatus.Missing } + assertFalse(Files.exists(cache.path)) - controller.cancelDownload(small) - recognizer.status(small).first { it == LocalSpeechModelStatus.Missing } - Files.list(directory.root.toPath()).use { assertEquals(0, it.count()) } - // Cleanup has finished before the UI exposes another Download model button. - controller.downloadModel(small) - recognizer.status(small).first { it == LocalSpeechModelStatus.Downloaded } - assertEquals(2, downloads) - assertTrue(cache.isValid()) - assertEquals(0, loads) + controller.downloadModel(model) + recognizer.status(model).first { it == LocalSpeechModelStatus.Downloaded } + assertTrue(cache.isComplete()) controller.updateConfig(local) - recognizer.status(small).first { it == LocalSpeechModelStatus.Ready } - assertEquals(1, loads) - controller.updateConfig(local.copy(provider = VoiceInputProvider.QWEN)) - releases.receive() - assertEquals(LocalSpeechModelStatus.Downloaded, recognizer.status(small).value) - assertEquals(2, downloads) + recognizer.status(model).first { it == LocalSpeechModelStatus.Ready } } } finally { lifetime.cancelAndJoin() @@ -331,74 +276,59 @@ class LocalSpeechRecognitionTest { } } - @Test - fun manualDownloadAutomaticallyLoadsWhenLocalServiceIsStillEnabled() = runBlocking { - val cache = store() - val started = CompletableDeferred() - val finish = CompletableDeferred() - var loads = 0 - val recognizer = DesktopLocalSpeechRecognizer(cache, supported = true, - download = { store, progress -> - started.complete(Unit) - finish.await() - store.install(ByteReadChannel(model), progress) - }, createEngine = { loads++; fakeEngine() }) - val lifetime = Job() - val controller = LocalSpeechModelController(CoroutineScope(coroutineContext + lifetime), recognizer) - try { - withTimeout(5_000) { - controller.updateConfig(VoiceInputConfig(enabled = true, provider = VoiceInputProvider.LOCAL_WHISPER)) - controller.downloadModel(small) - started.await() - assertEquals(0, loads) - finish.complete(Unit) - recognizer.status(small).first { it == LocalSpeechModelStatus.Ready } - assertEquals(1, loads) - assertEquals( - VoiceTranscriptionResult.Success("local speech"), - recognizer.transcribe(small, wav, "zh"), - ) - } - } finally { - lifetime.cancelAndJoin() - } - assertEquals(LocalSpeechModelStatus.Downloaded, recognizer.status(small).value) - } - @Test fun localServiceAcceptsNoCloudCredentialsAndCloudSelectionKeepsValidation() = runBlocking { - val store = store() - store.install(ByteReadChannel(model)) { _, _ -> } - val recognizer = DesktopLocalSpeechRecognizer(store, supported = true, createEngine = { fakeEngine() }) - assertTrue(recognizer.prepare(small)) - val config = VoiceInputConfig(provider = VoiceInputProvider.LOCAL_WHISPER, apiKey = "", baseUrl = "", model = "") - assertEquals(VoiceTranscriptionResult.Success("local speech"), transcribeVoiceAudio(config, wav, localRecognizer = recognizer)) - assertEquals(VoiceTranscriptionFailureReason.API_KEY_REQUIRED, - assertIs(transcribeVoiceAudio(config.copy(provider = VoiceInputProvider.QWEN), wav, localRecognizer = recognizer)).reason) + val cache = store() + cache.install(ByteReadChannel(modelBytes)) { _, _ -> } + cache.installAuxiliary(ByteReadChannel(tokens)) { _, _ -> } + val recognizer = JvmLocalSpeechRecognizer( + cache, + supported = true, + createEngine = { _, _ -> fakeEngine() }, + ) + assertTrue(recognizer.prepare(model)) + val config = VoiceInputConfig(provider = VoiceInputProvider.LOCAL_MODEL) + assertEquals( + VoiceTranscriptionResult.Success("local speech"), + transcribeVoiceAudio(config, wav, localRecognizer = recognizer), + ) + assertEquals( + VoiceTranscriptionFailureReason.API_KEY_REQUIRED, + assertIs( + transcribeVoiceAudio(config.copy(provider = VoiceInputProvider.QWEN), wav, localRecognizer = recognizer), + ).reason, + ) recognizer.release() } @Test fun cancellationDiscardsNativeResultAndDisposalWaitsForInference() = runBlocking { - val store = store() - store.install(ByteReadChannel(model)) { _, _ -> } + val cache = store() + cache.install(ByteReadChannel(modelBytes)) { _, _ -> } + cache.installAuxiliary(ByteReadChannel(tokens)) { _, _ -> } val started = CompletableDeferred() val finish = CountDownLatch(1) var closed = false - val recognizer = DesktopLocalSpeechRecognizer(store, supported = true, createEngine = { - object : LocalWhisperEngine { + val recognizer = JvmLocalSpeechRecognizer(cache, supported = true, createEngine = { _, _ -> + object : LocalSpeechEngine { override fun transcribe(samples: FloatArray, language: String): String { started.complete(Unit) check(finish.await(5, TimeUnit.SECONDS)) assertFalse(closed) return "stale text" } - override fun close() { closed = true } + + override fun close() { + closed = true + } } }) - assertTrue(recognizer.prepare(small)) + assertTrue(recognizer.prepare(model)) var published = false - val inference = launch { recognizer.transcribe(small, wav, "en"); published = true } + val inference = launch { + recognizer.transcribe(model, wav, "zh") + published = true + } withTimeout(5_000) { started.await() } inference.cancel() val release = async(Dispatchers.IO) { recognizer.release() } @@ -410,18 +340,21 @@ class LocalSpeechRecognitionTest { } @Test - fun convertsDifferentRecordingSampleRatesToWhisperPcm() { + fun convertsDifferentRecordingSampleRatesToModelPcm() { for (rate in listOf(8_000, 16_000, 44_100, 48_000)) { val audio = pcm16ToWav(ByteArray(rate * 2) { if (it % 2 == 0) 0 else 32 }, rate) - val samples = whisperPcmSamples(audio) + val samples = speechPcmSamples(audio) assertTrue(samples.size in 15_950..16_050, "rate=$rate samples=${samples.size}") assertEquals(0.25f, samples[samples.size / 2], 0.001f) } - assertTrue(runCatching { whisperPcmSamples(ByteArray(45)) }.isFailure) + assertTrue(runCatching { speechPcmSamples(ByteArray(45)) }.isFailure) } - private fun fakeEngine() = object : LocalWhisperEngine { + private fun fakeEngine() = object : LocalSpeechEngine { override fun transcribe(samples: FloatArray, language: String) = "local speech" override fun close() = Unit } + + private fun sha256(bytes: ByteArray): String = + MessageDigest.getInstance("SHA-256").digest(bytes).toHexString() } diff --git a/composeApp/src/desktopTest/kotlin/com/vrcmc/app/audio/LocalWhisperIntegrationTest.kt b/composeApp/src/desktopTest/kotlin/com/vrcmc/app/audio/LocalWhisperIntegrationTest.kt deleted file mode 100644 index 8122d3a..0000000 --- a/composeApp/src/desktopTest/kotlin/com/vrcmc/app/audio/LocalWhisperIntegrationTest.kt +++ /dev/null @@ -1,45 +0,0 @@ -package com.vrcmc.app - -import java.nio.file.Path -import kotlin.test.Test -import kotlin.test.assertIs -import kotlin.test.assertTrue -import kotlinx.coroutines.runBlocking -import org.junit.Assume.assumeTrue - -class LocalWhisperIntegrationTest { - @Test - fun downloadsVerifiesLoadsAndRecognizesAllModelsOffline() = runBlocking { - assumeTrue(System.getenv("VRCMC_LOCAL_ASR_INTEGRATION_TEST") == "1") - assumeTrue(localWhisperSupported()) - val root = Path.of("build", "local-asr-test").toAbsolutePath() - for (model in LocalWhisperModel.entries) { - val store = LocalWhisperModelStore( - path = root.resolve(model.modelFileName()), - expectedSize = model.modelSize(), - expectedHash = model.modelSha256(), - ) - val recognizer = DesktopLocalSpeechRecognizer( - stores = mapOf(model to store), - ) - try { - assertTrue(recognizer.downloadModel(model), recognizer.status(model).value.toString()) - assertTrue(recognizer.prepare(model), recognizer.status(model).value.toString()) - for ((fixture, language, expected) in listOf( - Triple("speech.wav", "en", "speech"), - Triple("speech-zh.wav", "zh", "语音"), - Triple("speech.wav", "auto", "speech"), - )) { - val wav = checkNotNull(javaClass.getResourceAsStream("/audio/$fixture")).use { it.readBytes() } - val result = assertIs( - recognizer.transcribe(model, wav, language), - ) - println("${model.displayName} ($language): ${result.text}") - assertTrue(result.text.contains(expected, ignoreCase = true), result.text) - } - } finally { - recognizer.release() - } - } - } -} diff --git a/composeApp/src/desktopTest/kotlin/com/vrcmc/app/audio/LocalWhisperQualityTest.kt b/composeApp/src/desktopTest/kotlin/com/vrcmc/app/audio/LocalWhisperQualityTest.kt deleted file mode 100644 index 0e970a2..0000000 --- a/composeApp/src/desktopTest/kotlin/com/vrcmc/app/audio/LocalWhisperQualityTest.kt +++ /dev/null @@ -1,247 +0,0 @@ -package com.vrcmc.app - -import java.io.ByteArrayInputStream -import java.io.ByteArrayOutputStream -import java.nio.file.Files -import java.nio.file.Path -import java.text.Normalizer -import javazoom.jl.decoder.Bitstream -import javazoom.jl.decoder.Decoder -import javazoom.jl.decoder.SampleBuffer -import kotlin.math.roundToInt -import kotlin.random.Random -import kotlin.test.Test -import kotlin.test.assertIs -import kotlin.test.assertTrue -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.currentCoroutineContext -import kotlinx.coroutines.ensureActive -import kotlinx.serialization.json.* -import org.junit.Assume.assumeTrue - -/** Opt-in quality check. Synthetic fixtures are generated once and reused from build/. - * Recognition is entirely local; only these fixed, public test sentences are sent to Edge TTS. - */ -class LocalWhisperQualityTest { - private data class Utterance(val id: String, val language: String, val voice: String, val text: String) - private val model = LocalWhisperModel.SMALL_Q5_1 - private val utterances = listOf( - Utterance("zh-room", "zh", "zh-CN-XiaoxiaoNeural", "你好,我刚刚加入这个房间,可以听到我的声音吗?"), - Utterance("zh-controller", "zh", "zh-CN-YunxiNeural", "请等我一下,我的手柄没电了,需要重新连接。"), - Utterance("zh-photo", "zh", "zh-CN-XiaoxiaoNeural", "这个世界很漂亮,我们一起去那边拍张照片吧。"), - Utterance("ja-voice", "ja", "ja-JP-NanamiNeural", "こんにちは、私の声は聞こえますか。少しゆっくり話してください。"), - Utterance("ja-controller", "ja", "ja-JP-KeitaNeural", "ちょっと待ってください。コントローラーの電池が切れました。"), - Utterance("ja-photo", "ja", "ja-JP-NanamiNeural", "このワールドはとてもきれいですね。一緒に写真を撮りましょう。"), - Utterance("en-room", "en", "en-US-AriaNeural", "Hi, I just joined this room. Can you hear my microphone?"), - Utterance("en-controller", "en", "en-US-GuyNeural", "Please wait a moment. My controller ran out of battery and I need to reconnect."), - Utterance("en-photo", "en", "en-US-AriaNeural", "This world looks beautiful. Let's take a picture together over there."), - ) - - @Test - fun chineseJapaneseAndEnglishConversationAccuracyAndSpeed() = runBlocking { - assumeTrue(System.getenv("VRCMC_LOCAL_ASR_QUALITY_TEST") == "1") - assumeTrue(localWhisperSupported()) - val root = Path.of("build", "local-asr-test").toAbsolutePath() - Files.createDirectories(root) - val recognizer = DesktopLocalSpeechRecognizer(LocalWhisperModelStore(root.resolve("ggml-small-q5_1.bin"))) - val report = StringBuilder("# 本地 Whisper 中日英识别验证\n\n") - report.append("模型:Whisper Small Q5_1;CPU 推理,最多 6 线程。样本为固定测试句的 Edge TTS 合成语音,每种语言包含男女声。\n\n") - report.append("中日文计算去标点后的字错误率(CER),英文计算词错误率(WER)。噪声样本叠加固定种子的约 20 dB 信噪比白噪声;自动检测另取每种语言一条。耗时作为硬件相关的测量结果记录,不作为准确率测试的通过条件。\n\n") - val errors = mutableListOf>() - val failures = mutableListOf() - try { - assertTrue(recognizer.downloadModel(model), recognizer.status(model).value.toString()) - assertTrue(recognizer.prepare(model), recognizer.status(model).value.toString()) - for (utterance in utterances) { - val mp3 = root.resolve("${utterance.id}.mp3") - if (!Files.isRegularFile(mp3)) Files.write(mp3, synthesizeFixture(utterance)) - val samples = whisperPcmSamples(decodeMp3(Files.readAllBytes(mp3))) - val variants = buildList { - add("clean" to samples) - add("noise20db" to withNoise(samples)) - if (utterance.id in setOf("zh-room", "ja-voice", "en-room")) add("auto" to samples) - } - for ((variant, audio) in variants) { - val language = if (variant == "auto") "auto" else utterance.language - val started = System.nanoTime() - val result = assertIs( - recognizer.transcribe(model, toWav(audio), language), - ) - val elapsed = (System.nanoTime() - started) / 1_000_000_000.0 - val duration = audio.size / 16_000.0 - val rate = errorRate(utterance.text, result.text, utterance.language) - errors += "${utterance.language}/$variant" to rate - val info = "${utterance.id}/$variant: error=${percent(rate)}, audio=${seconds(duration)}s, inference=${seconds(elapsed)}s, RTF=${seconds(elapsed / duration)}" - println("$info\nExpected: ${utterance.text}\nActual: ${result.text}") - report.append("## ${utterance.id} / $variant\n\n- 原文:${utterance.text}\n- 识别:${result.text}\n- 错误率:${percent(rate)};音频 ${seconds(duration)} 秒,识别 ${seconds(elapsed)} 秒,耗时/音频时长 ${seconds(elapsed / duration)}。\n\n") - Files.writeString(root.resolve("quality-report.md"), report.toString()) - if (rate > 0.20) failures += "$info: ${result.text}" - } - } - report.append("## 汇总\n\n| 语言 / 场景 | 平均错误率 |\n| --- | --- |\n") - for ((key, entries) in errors.groupBy { it.first }) { - val average = entries.map { it.second }.average() - report.append("| $key | ${percent(average)} |\n") - if (average > 0.10) failures += "$key average error rate ${percent(average)}" - } - assertTrue(failures.isEmpty(), failures.joinToString("\n")) - } finally { - recognizer.release() - Files.writeString(root.resolve("quality-report.md"), report.toString()) - } - } - - @Test - fun humanSpeechInThreeLanguagesIncludingProductionAudioChunks() = runBlocking { - assumeTrue(System.getenv("VRCMC_LOCAL_ASR_HUMAN_TEST") == "1") - assumeTrue(localWhisperSupported()) - val root = Path.of("build", "local-asr-test").toAbsolutePath() - val recordings = root.resolve("fleurs") - check(Files.isRegularFile(recordings.resolve("manifest.json"))) { "Run scripts/download-local-asr-fixtures.py first" } - val manifest = Json.parseToJsonElement(Files.readString(recordings.resolve("manifest.json"))).jsonArray - val recognizer = DesktopLocalSpeechRecognizer(LocalWhisperModelStore(root.resolve("ggml-small-q5_1.bin"))) - val report = StringBuilder("# 中日英真人语音验证\n\nFLEURS(google/fleurs,CC-BY-4.0)固定版本的测试集,每种语言按归档顺序取前 3 段;详细来源见 fleurs/manifest.json。完整音频保持原始音量。额外对每种语言第一段运行应用的 VAD、6 秒重叠分块和字幕句子合并;分块测试先统一峰值至 0.8,避免低音量语音低于配置的采集门限。\n\n") - val rates = mutableListOf>() - val failures = mutableListOf() - val chunkedLanguages = mutableSetOf() - try { - assertTrue(recognizer.downloadModel(model), recognizer.status(model).value.toString()) - assertTrue(recognizer.prepare(model), recognizer.status(model).value.toString()) - for (item in manifest) { - val obj = item.jsonObject - val language = obj.getValue("language").jsonPrimitive.content - val file = obj.getValue("file").jsonPrimitive.content - val expected = obj.getValue("text").jsonPrimitive.content - val wav = Files.readAllBytes(recordings.resolve(file)) - val modes = if (chunkedLanguages.add(language)) listOf("whole", "chunks") else listOf("whole") - for (mode in modes) { - val started = System.nanoTime() - val actual = if (mode == "whole") assertIs( - recognizer.transcribe(model, wav, language), - ).text - else recognizeChunks(recognizer, wav, language) - val elapsed = (System.nanoTime() - started) / 1_000_000_000.0 - val rate = errorRate(expected, actual, language) - rates += "$language/$mode" to rate - report.append("## $file / $mode\n\n- 原文:$expected\n- 识别:$actual\n- 错误率:${percent(rate)};处理耗时 ${seconds(elapsed)} 秒。\n\n") - Files.writeString(root.resolve("human-quality-report.md"), report.toString()) - println("FLEURS $file/$mode error=${percent(rate)} seconds=${seconds(elapsed)}\n$actual") - if (rate > 0.30) failures += "$file/$mode: ${percent(rate)}" - } - } - report.append("## 汇总\n\n| 语言 / 模式 | 平均错误率 |\n| --- | --- |\n") - for ((key, values) in rates.groupBy { it.first }) { - val average = values.map { it.second }.average() - report.append("| $key | ${percent(average)} |\n") - if (average > 0.15) failures += "$key average ${percent(average)}" - } - assertTrue(failures.isEmpty(), failures.joinToString("\n")) - } finally { - recognizer.release() - Files.writeString(root.resolve("human-quality-report.md"), report.toString()) - } - } - - private suspend fun recognizeChunks(recognizer: LocalSpeechRecognizer, wav: ByteArray, language: String): String { - val samples = whisperPcmSamples(wav) - val peak = samples.maxOf { kotlin.math.abs(it) }.coerceAtLeast(0.0001f) - val converted = toWav(FloatArray(samples.size) { samples[it] * (0.8f / peak) }) - val pcm = converted.copyOfRange(44, converted.size) - val chunks = mutableListOf() - SileroSpeechDetector().use { detector -> - val processor = VoiceCaptureProcessor( - config = VoiceInputConfig(sampleRate = 16_000), onSpeechState = {}, onPartial = {}, - onFinal = {}, onNoSpeech = {}, onAutoStop = {}, continuous = true, emitPartials = false, - speechDetector = detector::isSpeech, onChunk = chunks::add, - ) - processor.accept(pcm) - processor.accept(ByteArray(32_000)) - processor.finish() - } - val assembler = SentenceTextAssembler() - val completed = mutableListOf() - for (chunk in chunks) { - chunk.wav?.let { - val text = assertIs( - recognizer.transcribe(model, it, language), - ).text - completed += assembler.append(text, chunk.overlapSamples > 0) - } - if (chunk.isFinal) completed += assembler.finish() - } - return completed.joinToString(" ") - } - - private suspend fun synthesizeFixture(utterance: Utterance): ByteArray { - var lastFailure: Exception? = null - repeat(3) { - try { return EdgeTtsService.synthesize(utterance.text, utterance.voice) } - catch (error: Exception) { - currentCoroutineContext().ensureActive() - lastFailure = error - } - } - throw checkNotNull(lastFailure) - } - - private fun decodeMp3(mp3: ByteArray): ByteArray { - val stream = Bitstream(ByteArrayInputStream(mp3)) - val decoder = Decoder() - val pcm = ByteArrayOutputStream() - var sampleRate = 24_000 - try { - while (true) { - val header = stream.readFrame() ?: break - val samples = decoder.decodeFrame(header, stream) as SampleBuffer - check(samples.channelCount == 1) - sampleRate = samples.sampleFrequency - for (index in 0 until samples.bufferLength) { - val value = samples.buffer[index].toInt() - pcm.write(value and 255) - pcm.write((value shr 8) and 255) - } - stream.closeFrame() - } - } finally { stream.close() } - return pcm16ToWav(pcm.toByteArray(), sampleRate) - } - - private fun withNoise(samples: FloatArray): FloatArray { - val rms = kotlin.math.sqrt(samples.map { it.toDouble() * it }.average()) - val amplitude = (rms / 10 * kotlin.math.sqrt(3.0)).toFloat() - val random = Random(42) - return FloatArray(samples.size) { (samples[it] + (random.nextFloat() * 2 - 1) * amplitude).coerceIn(-1f, 1f) } - } - - private fun toWav(samples: FloatArray): ByteArray { - val pcm = ByteArray(samples.size * 2) - samples.forEachIndexed { index, value -> - val signed = (value * 32768).roundToInt().coerceIn(-32768, 32767) - pcm[index * 2] = signed.toByte() - pcm[index * 2 + 1] = (signed shr 8).toByte() - } - return pcm16ToWav(pcm, 16_000) - } - - private fun errorRate(expected: String, actual: String, language: String): Double { - fun units(text: String): List { - val normalized = Normalizer.normalize(text, Normalizer.Form.NFKC).lowercase() - return if (language == "en") normalized.replace("’", "'").replace("'", "") - .split(Regex("[^a-z0-9]+" )).filter(String::isNotBlank) - else normalized.filter(Char::isLetterOrDigit).map(Char::toString) - } - val a = units(expected) - val b = units(actual) - var previous = IntArray(b.size + 1) { it } - a.forEachIndexed { i, value -> - val current = IntArray(b.size + 1) - current[0] = i + 1 - b.forEachIndexed { j, other -> current[j + 1] = minOf(current[j] + 1, previous[j + 1] + 1, previous[j] + if (value == other) 0 else 1) } - previous = current - } - return previous.last().toDouble() / a.size.coerceAtLeast(1) - } - - private fun percent(value: Double) = "${(value * 10_000).roundToInt() / 100.0}%" - private fun seconds(value: Double) = ((value * 100).roundToInt() / 100.0).toString() -} diff --git a/composeApp/src/desktopTest/kotlin/com/vrcmc/app/audio/SenseVoiceRecognitionTest.kt b/composeApp/src/desktopTest/kotlin/com/vrcmc/app/audio/SenseVoiceRecognitionTest.kt new file mode 100644 index 0000000..3478652 --- /dev/null +++ b/composeApp/src/desktopTest/kotlin/com/vrcmc/app/audio/SenseVoiceRecognitionTest.kt @@ -0,0 +1,78 @@ +package com.vrcmc.app + +import java.nio.file.Path +import kotlin.math.PI +import kotlin.math.sin +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertTrue +import kotlinx.coroutines.runBlocking +import org.junit.Assume.assumeTrue + +class SenseVoiceRecognitionTest { + @Test + fun fbankAndLfrProduceTheModelFeatureShape() { + val samples = FloatArray(16_000) { index -> + (sin(2.0 * PI * 220.0 * index / 16_000.0) * 0.2).toFloat() + } + val fbank = localSpeechFbank(samples) + assertEquals(98 * 80, fbank.size) + assertTrue(fbank.all(Float::isFinite)) + + val lfr = localSpeechApplyLfr(fbank, 80, 7, 6) + assertEquals(17 * 560, lfr.size) + } + + @Test + fun ctcDecodeCollapsesRepeatsAndSkipsMetadataTokens() { + val tokens = listOf( + "", + "<|zh|>", + "<|NEUTRAL|>", + "<|Speech|>", + "<|withitn|>", + "你", + "好", + ) + val ids = intArrayOf(1, 2, 3, 4, 5, 5, 0, 6, 6) + val logits = FloatArray(ids.size * tokens.size) + ids.forEachIndexed { frame, id -> + logits[frame * tokens.size + id] = 1f + } + + assertEquals( + "你好", + decodeCtcLogits(logits, ids.size, tokens.size, tokens, blankId = 0), + ) + } + + @Test + fun cachedInt8ModelRecognizesChineseFixture() = runBlocking { + assumeTrue(System.getenv("VRCMC_SENSE_VOICE_INTEGRATION_TEST") == "1") + val model = LocalSpeechModel.SENSE_VOICE_SMALL_INT8 + val path = Path.of("..", "build", "sensevoice-test", model.modelFileName()) + val store = model.createStore(path) + val modelValid = store.isValid() + val tokensValid = store.isAuxiliaryValid() + assertTrue( + modelValid && tokensValid, + "Missing cached SenseVoice model or tokens: model=${path.toAbsolutePath()} ($modelValid), " + + "tokens=${store.auxiliaryPath?.toAbsolutePath()} ($tokensValid)", + ) + val recognizer = JvmLocalSpeechRecognizer(mapOf(model to store), supported = true) + try { + assertTrue(recognizer.prepare(model), recognizer.status(model).value.toString()) + val wav = checkNotNull(javaClass.getResourceAsStream("/audio/speech-zh.wav")).use { + it.readBytes() + } + val result = assertIs( + recognizer.transcribe(model, wav, "zh"), + ) + println("SenseVoice zh: ${result.text}") + assertTrue(result.text.isNotBlank()) + } finally { + recognizer.release() + } + } +} diff --git a/composeApp/src/desktopTest/kotlin/com/vrcmc/app/ui/components/VoiceInputServiceSectionTest.kt b/composeApp/src/desktopTest/kotlin/com/vrcmc/app/ui/components/VoiceInputServiceSectionTest.kt index d009234..6afa5af 100644 --- a/composeApp/src/desktopTest/kotlin/com/vrcmc/app/ui/components/VoiceInputServiceSectionTest.kt +++ b/composeApp/src/desktopTest/kotlin/com/vrcmc/app/ui/components/VoiceInputServiceSectionTest.kt @@ -38,11 +38,11 @@ class VoiceInputServiceSectionTest { } } compose.onNodeWithText(strings.voiceInputProvider).performClick() - compose.onNodeWithText(strings.localWhisper).performClick() + compose.onNodeWithText(strings.localModel).performClick() compose.onNodeWithText(strings.qwenApiKey).assertDoesNotExist() compose.onNodeWithText("Base URL").assertDoesNotExist() - compose.onNodeWithText(LocalWhisperModel.SMALL_Q5_1.displayLabel).assertIsDisplayed() - compose.runOnIdle { assertEquals(original.copy(provider = VoiceInputProvider.LOCAL_WHISPER), config) } + compose.onNodeWithText(LocalSpeechModel.SENSE_VOICE_SMALL_INT8.displayLabel).assertIsDisplayed() + compose.runOnIdle { assertEquals(original.copy(provider = VoiceInputProvider.LOCAL_MODEL), config) } compose.onNodeWithText(strings.voiceInputProvider).performClick() compose.onNodeWithText("Fun-ASR").performClick() compose.onNodeWithText(strings.qwenApiKey).assertIsDisplayed() @@ -50,12 +50,12 @@ class VoiceInputServiceSectionTest { } @Test - fun selectingMediumUpdatesConfigShowsSizeAndDownloadsMedium() { + fun senseVoiceModelIsShownAndDownloadsInt8Model() { val recognizer = DownloadTestRecognizer() var config by mutableStateOf( - VoiceInputConfig(enabled = true, provider = VoiceInputProvider.LOCAL_WHISPER), + VoiceInputConfig(enabled = true, provider = VoiceInputProvider.LOCAL_MODEL), ) - var requestedModel: LocalWhisperModel? = null + var requestedModel: LocalSpeechModel? = null compose.setContent { MaterialTheme { Column(Modifier.width(480.dp).verticalScroll(rememberScrollState())) { @@ -70,16 +70,43 @@ class VoiceInputServiceSectionTest { } } - compose.onNodeWithText(LocalWhisperModel.SMALL_Q5_1.displayLabel).performClick() - compose.onNodeWithText(LocalWhisperModel.MEDIUM_Q5_0.displayLabel).performClick() - - compose.onNodeWithText("Whisper Medium Q5_0 · 539 MB").assertIsDisplayed() + compose.onNodeWithText("SenseVoice Small INT8 · 240 MB").assertIsDisplayed() + compose.onNodeWithText(strings.localModelDownload).performClick() compose.runOnIdle { - assertEquals(LocalWhisperModel.MEDIUM_Q5_0, config.localWhisperModel) + assertEquals(LocalSpeechModel.SENSE_VOICE_SMALL_INT8, config.localSpeechModel) + assertEquals(LocalSpeechModel.SENSE_VOICE_SMALL_INT8, requestedModel) + } + } + + @Test + fun selectingFunAsrNanoUpdatesConfigAndDownloadsModel() { + val recognizer = DownloadTestRecognizer() + var config by mutableStateOf( + VoiceInputConfig(enabled = true, provider = VoiceInputProvider.LOCAL_MODEL), + ) + var requestedModel: LocalSpeechModel? = null + compose.setContent { + MaterialTheme { + Column(Modifier.width(480.dp).verticalScroll(rememberScrollState())) { + VoiceInputServiceSection( + config = config, + strings = strings, + onUpdate = { config = it(config) }, + onDownloadLocalModel = { requestedModel = it }, + localRecognizer = recognizer, + ) + } + } } + + compose.onNodeWithText(LocalSpeechModel.SENSE_VOICE_SMALL_INT8.displayLabel).performClick() + compose.onNodeWithText(LocalSpeechModel.FUN_ASR_NANO_2512_INT8.displayLabel).performClick() + compose.onNodeWithText("Fun-ASR-Nano 2512 INT8 · 265 MB").assertIsDisplayed() + compose.onNodeWithText(strings.funAsrNanoHint).assertIsDisplayed() compose.onNodeWithText(strings.localModelDownload).performClick() compose.runOnIdle { - assertEquals(LocalWhisperModel.MEDIUM_Q5_0, requestedModel) + assertEquals(LocalSpeechModel.FUN_ASR_NANO_2512_INT8, config.localSpeechModel) + assertEquals(LocalSpeechModel.FUN_ASR_NANO_2512_INT8, requestedModel) } } @@ -93,7 +120,7 @@ class VoiceInputServiceSectionTest { Surface { Column(Modifier.width(480.dp).padding(16.dp)) { LocalSpeechModelSettings( - model = LocalWhisperModel.SMALL_Q5_1, + model = LocalSpeechModel.SENSE_VOICE_SMALL_INT8, status = status, supported = true, strings = strings, @@ -109,10 +136,10 @@ class VoiceInputServiceSectionTest { compose.onNodeWithText(strings.localModelDownload).performClick() compose.runOnIdle { assertEquals(1, downloads) - status = LocalSpeechModelStatus.Downloading(95_000_000, 190_000_000) + status = LocalSpeechModelStatus.Downloading(120_000_000, 240_000_000) } - compose.onNodeWithText("正在下载模型 50% · 95 / 190 MB").assertIsDisplayed() - compose.onNodeWithText(LocalWhisperModel.SMALL_Q5_1.displayLabel).assertIsNotEnabled() + compose.onNodeWithText("正在下载模型 50% · 120 / 240 MB").assertIsDisplayed() + compose.onNodeWithText(LocalSpeechModel.SENSE_VOICE_SMALL_INT8.displayLabel).assertIsNotEnabled() compose.onNodeWithText(strings.localModelCancelDownload).performClick() compose.runOnIdle { assertEquals(1, cancellations) } val output = File("build/test-screenshots/local-speech-model.png") @@ -137,7 +164,7 @@ class VoiceInputServiceSectionTest { @Test fun downloadAndCancelRemainAvailableAcrossServiceSwitchDisableAndPageNavigation() { val recognizer = DownloadTestRecognizer() - var config by mutableStateOf(VoiceInputConfig(enabled = true, provider = VoiceInputProvider.LOCAL_WHISPER)) + var config by mutableStateOf(VoiceInputConfig(enabled = true, provider = VoiceInputProvider.LOCAL_MODEL)) var pageVisible by mutableStateOf(true) compose.setContent { val scope = rememberCoroutineScope() @@ -175,13 +202,13 @@ class VoiceInputServiceSectionTest { private class DownloadTestRecognizer : LocalSpeechRecognizer by UnsupportedLocalSpeechRecognizer { override val supported = true - private val statuses = LocalWhisperModel.entries.associateWith { + private val statuses = LocalSpeechModel.entries.associateWith { MutableStateFlow(LocalSpeechModelStatus.Missing) } var downloads = 0 var cancellations = 0 - override fun status(model: LocalWhisperModel) = statuses.getValue(model) - override suspend fun downloadModel(model: LocalWhisperModel): Boolean { + override fun status(model: LocalSpeechModel) = statuses.getValue(model) + override suspend fun downloadModel(model: LocalSpeechModel): Boolean { downloads++ val status = statuses.getValue(model) status.value = LocalSpeechModelStatus.Downloading(95_000_000, model.downloadSizeMb * 1_000_000L) diff --git a/composeApp/src/desktopTest/resources/audio/README.md b/composeApp/src/desktopTest/resources/audio/README.md index 83ed7b5..60bcbf7 100644 --- a/composeApp/src/desktopTest/resources/audio/README.md +++ b/composeApp/src/desktopTest/resources/audio/README.md @@ -8,8 +8,6 @@ Text: “Testing speech detection. Only spoken words should be translated.” The service smoke test is explicitly enabled with `VRCMC_LISTENING_API_SMOKE=1`; it uses the locally configured ASR/translation services and sends only this known fixture. Hardware loopback tests require `VRCMC_LOOPBACK_SMOKE=1` and play the English fixture locally. Normal tests use the actual VAD model with fake service functions and never access cloud services. -`VRCMC_LOCAL_ASR_INTEGRATION_TEST=1` enables `LocalWhisperIntegrationTest`: it downloads and verifies every selectable local Whisper model into `composeApp/build/local-asr-test`, then recognizes both fixtures locally and checks automatic language detection with each model. It does not read API credentials or upload audio. +`VRCMC_SENSE_VOICE_INTEGRATION_TEST=1` enables the cached SenseVoice INT8 integration test. It verifies the Chinese fixture and does not read API credentials or upload audio. -`VRCMC_LOCAL_ASR_QUALITY_TEST=1` enables the three-language conversation benchmark in `LocalWhisperQualityTest`. Nine fixed Chinese/Japanese/English sentences use six Edge TTS voices (the text is sent only to Edge TTS to generate test fixtures). Clean, 20 dB SNR noise and automatic-language variants are recognized locally. Cached audio and per-case CER/WER/latency results stay in `composeApp/build/local-asr-test/quality-report.md`. Accuracy gates are at most 20% error per case and 10% mean per language/scenario; latency is recorded separately because it depends on the host CPU and concurrent workload. - -For human speech, first run `python scripts/download-local-asr-fixtures.py` from the repository root, then set `VRCMC_LOCAL_ASR_HUMAN_TEST=1`. The script streams the first three test recordings per language from the pinned [Google FLEURS dataset](https://huggingface.co/datasets/google/fleurs), licensed under [CC-BY-4.0](https://creativecommons.org/licenses/by/4.0/). Audio, reference text and attribution stay in the ignored build directory. The test recognizes all nine original recordings and additionally runs VAD, six-second overlapping chunks and sentence assembly for one recording per language. The chunked variants normalize peak volume to 0.8 to meet the application's recording threshold. Results go to `human-quality-report.md`; accuracy gates are 30% per case and 15% per language/mode. These small deterministic samples are regression checks, not a claim about all speakers, accents or environments. +`VRCMC_FUN_ASR_INTEGRATION_TEST=1` enables the cached Fun-ASR-Nano INT8 integration test against its official Chinese sample. diff --git a/composeApp/src/jvmLocalMain/kotlin/com/vrcmc/app/audio/FunAsrNanoRecognition.kt b/composeApp/src/jvmLocalMain/kotlin/com/vrcmc/app/audio/FunAsrNanoRecognition.kt new file mode 100644 index 0000000..022ba32 --- /dev/null +++ b/composeApp/src/jvmLocalMain/kotlin/com/vrcmc/app/audio/FunAsrNanoRecognition.kt @@ -0,0 +1,69 @@ +package com.vrcmc.app + +import ai.onnxruntime.OnnxTensor +import ai.onnxruntime.OrtEnvironment +import ai.onnxruntime.OrtSession +import java.nio.FloatBuffer +import java.nio.charset.StandardCharsets +import java.nio.file.Files +import java.nio.file.Path +import java.util.Base64 + +internal class FunAsrNanoEngine(model: Path) : LocalSpeechEngine { + private val environment = OrtEnvironment.getEnvironment() + private val session = OrtSession.SessionOptions().use { options -> + options.setInterOpNumThreads(1) + options.setIntraOpNumThreads( + Runtime.getRuntime().availableProcessors().let { (it / 2).coerceIn(1, 6) }, + ) + environment.createSession(model.toString(), options) + } + private val metadata = session.metadata.customMetadata + private val lfrWindowSize = metadata.getValue("lfr_window_size").toInt() + private val lfrWindowShift = metadata.getValue("lfr_window_shift").toInt() + private val featureDimension = localSpeechMelBins * lfrWindowSize + private val blankId = metadata.getValue("blank_id").toInt() + private val tokens = Files.readAllLines( + model.resolveSibling("tokens.txt"), + StandardCharsets.UTF_8, + ).map { line -> + val encoded = line.substringBeforeLast(' ') + Base64.getDecoder().decode(encoded).toString(StandardCharsets.UTF_8) + } + private val melBanks = localSpeechMelBanks() + + override fun transcribe(samples: FloatArray, language: String): String { + val fbank = localSpeechFbank(samples, melBanks) + if (fbank.isEmpty()) return "" + val features = localSpeechApplyLfr(fbank, localSpeechMelBins, lfrWindowSize, lfrWindowShift) + val frames = features.size / featureDimension + if (frames == 0) return "" + val logits = try { + OnnxTensor.createTensor( + environment, + FloatBuffer.wrap(features), + longArrayOf(1, frames.toLong(), featureDimension.toLong()), + ).use { x -> + session.run(mapOf("x" to x)).use { result -> + val output = result.get("logits").orElseThrow() as OnnxTensor + val values = output.floatBuffer + val shape = output.info.shape + val copied = FloatArray(values.remaining()) + values.get(copied) + CtcLogits(copied, shape[1].toInt(), shape[2].toInt()) + } + } + } catch (error: Exception) { + throw IllegalStateException("Fun-ASR-Nano inference failed", error) + } + return decodeCtcLogits( + logits.values, + logits.frames, + logits.vocabularySize, + tokens, + blankId = blankId, + ) + } + + override fun close() = session.close() +} diff --git a/composeApp/src/jvmLocalMain/kotlin/com/vrcmc/app/audio/JvmLocalSpeechRecognition.kt b/composeApp/src/jvmLocalMain/kotlin/com/vrcmc/app/audio/JvmLocalSpeechRecognition.kt new file mode 100644 index 0000000..5605a18 --- /dev/null +++ b/composeApp/src/jvmLocalMain/kotlin/com/vrcmc/app/audio/JvmLocalSpeechRecognition.kt @@ -0,0 +1,221 @@ +package com.vrcmc.app + +import java.nio.file.Path +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext + +internal interface LocalSpeechEngine : AutoCloseable { + fun transcribe(samples: FloatArray, language: String): String +} + +internal class JvmLocalSpeechRecognizer( + private val stores: Map, + override val supported: Boolean = true, + private val download: suspend ( + LocalSpeechModel, + LocalSpeechModelStore, + (Long, Long) -> Unit, + ) -> Unit = ::downloadSpeechModel, + private val createEngine: (LocalSpeechModel, Path) -> LocalSpeechEngine = ::createLocalSpeechEngine, +) : LocalSpeechRecognizer { + internal constructor( + store: LocalSpeechModelStore, + supported: Boolean = true, + download: suspend (LocalSpeechModelStore, (Long, Long) -> Unit) -> Unit = { cache, progress -> + downloadSpeechModel(LocalSpeechModel.SENSE_VOICE_SMALL_INT8, cache, progress) + }, + createEngine: (LocalSpeechModel, Path) -> LocalSpeechEngine = ::createLocalSpeechEngine, + ) : this( + stores = mapOf(LocalSpeechModel.SENSE_VOICE_SMALL_INT8 to store), + supported = supported, + download = { _, cache, progress -> download(cache, progress) }, + createEngine = createEngine, + ) + + // Loading, inference and disposal share a lock: microphone and system audio may overlap. + private val mutex = Mutex() + private val downloadMutexes = LocalSpeechModel.entries.associateWith { Mutex() } + private val statuses = LocalSpeechModel.entries.associateWith { + MutableStateFlow(LocalSpeechModelStatus.Missing) + } + private var engine: LocalSpeechEngine? = null + private var loadedModel: LocalSpeechModel? = null + + override fun status(model: LocalSpeechModel) = statuses.getValue(model).asStateFlow() + + override suspend fun downloadModel(model: LocalSpeechModel): Boolean = withContext(Dispatchers.IO) { + if (!supported) return@withContext false + val store = stores[model] ?: return@withContext false + val downloadMutex = downloadMutexes.getValue(model) + if (!downloadMutex.tryLock()) return@withContext false + val modelStatus = statuses.getValue(model) + try { + val alreadyLoaded = mutex.withLock { + (engine != null && loadedModel == model).also { loaded -> + if (!loaded) { + modelStatus.value = LocalSpeechModelStatus.Downloading(0, store.expectedTotalSize) + } + } + } + if (alreadyLoaded) return@withContext true + if (store.isComplete()) { + mutex.withLock { modelStatus.value = cachedStatus(model) } + return@withContext true + } + // Network IO never holds the inference lock; service changes may release the engine. + download(model, store) { received, total -> + modelStatus.value = LocalSpeechModelStatus.Downloading(received, total) + } + currentCoroutineContext().ensureActive() + mutex.withLock { modelStatus.value = cachedStatus(model) } + true + } catch (error: CancellationException) { + withContext(NonCancellable) { + val valid = store.isComplete() + mutex.withLock { + modelStatus.value = when { + engine != null && loadedModel == model -> LocalSpeechModelStatus.Ready + valid -> LocalSpeechModelStatus.Downloaded + else -> LocalSpeechModelStatus.Missing + } + } + } + throw error + } catch (error: Exception) { + mutex.withLock { + modelStatus.value = LocalSpeechModelStatus.Failed(error.message?.take(300).orEmpty()) + } + false + } finally { + downloadMutex.unlock() + } + } + + override suspend fun prepare(model: LocalSpeechModel): Boolean = withContext(Dispatchers.IO) { + mutex.withLock { + if (!supported) return@withLock false + val modelStatus = statuses.getValue(model) + if ( + engine != null && loadedModel == model && + modelStatus.value == LocalSpeechModelStatus.Ready + ) return@withLock true + if (modelStatus.value is LocalSpeechModelStatus.Downloading) return@withLock false + if (engine != null) closeEngine() + val store = stores[model] + if (store == null) { + modelStatus.value = LocalSpeechModelStatus.Missing + return@withLock false + } + modelStatus.value = LocalSpeechModelStatus.Preparing + var cached = false + try { + if (!store.isComplete()) { + modelStatus.value = LocalSpeechModelStatus.Missing + return@withLock false + } + cached = true + currentCoroutineContext().ensureActive() + engine = createEngine(model, store.path) + loadedModel = model + currentCoroutineContext().ensureActive() + modelStatus.value = LocalSpeechModelStatus.Ready + true + } catch (error: CancellationException) { + closeEngine() + modelStatus.value = if (cached) LocalSpeechModelStatus.Downloaded else LocalSpeechModelStatus.Missing + throw error + } catch (error: Exception) { + preparationFailed(model, error) + } catch (error: LinkageError) { + preparationFailed(model, error) + } + } + } + + private fun preparationFailed(model: LocalSpeechModel, error: Throwable): Boolean { + closeEngine() + statuses.getValue(model).value = LocalSpeechModelStatus.Failed(error.message?.take(300).orEmpty()) + return false + } + + override suspend fun transcribe( + model: LocalSpeechModel, + wav: ByteArray, + language: String, + ): VoiceTranscriptionResult = + withContext(Dispatchers.IO) { + mutex.withLock { + if (!supported) { + return@withLock VoiceTranscriptionResult.Failure( + reason = VoiceTranscriptionFailureReason.LOCAL_UNSUPPORTED, + ) + } + val loaded = engine.takeIf { + loadedModel == model && statuses.getValue(model).value == LocalSpeechModelStatus.Ready + } ?: return@withLock VoiceTranscriptionResult.Failure( + reason = VoiceTranscriptionFailureReason.LOCAL_MODEL_NOT_READY, + ) + if (wav.size <= 44) { + return@withLock VoiceTranscriptionResult.Failure( + reason = VoiceTranscriptionFailureReason.NO_AUDIO, + ) + } + try { + val samples = speechPcmSamples(wav) + currentCoroutineContext().ensureActive() + val text = loaded.transcribe(samples, language).trim() + currentCoroutineContext().ensureActive() + if (text.isBlank()) VoiceTranscriptionResult.Failure( + reason = VoiceTranscriptionFailureReason.NO_AUDIO, + ) else VoiceTranscriptionResult.Success(text) + } catch (error: CancellationException) { + throw error + } catch (error: Exception) { + VoiceTranscriptionResult.Failure( + error.message.orEmpty(), + VoiceTranscriptionFailureReason.LOCAL_RECOGNITION_FAILED, + ) + } catch (error: LinkageError) { + VoiceTranscriptionResult.Failure( + error.message.orEmpty(), + VoiceTranscriptionFailureReason.LOCAL_RECOGNITION_FAILED, + ) + } + } + } + + override suspend fun release() = withContext(Dispatchers.IO) { + mutex.withLock { + if (engine != null) closeEngine() + } + } + + private fun cachedStatus(model: LocalSpeechModel): LocalSpeechModelStatus = + if (engine != null && loadedModel == model) LocalSpeechModelStatus.Ready + else LocalSpeechModelStatus.Downloaded + + private fun closeEngine() { + val previous = engine + val previousModel = loadedModel + engine = null + loadedModel = null + if (previousModel != null && statuses.getValue(previousModel).value == LocalSpeechModelStatus.Ready) { + statuses.getValue(previousModel).value = LocalSpeechModelStatus.Downloaded + } + previous?.close() + } +} + +private fun createLocalSpeechEngine(model: LocalSpeechModel, path: Path): LocalSpeechEngine = + when (model) { + LocalSpeechModel.SENSE_VOICE_SMALL_INT8 -> SenseVoiceEngine(path) + LocalSpeechModel.FUN_ASR_NANO_2512_INT8 -> FunAsrNanoEngine(path) + } diff --git a/composeApp/src/jvmLocalMain/kotlin/com/vrcmc/app/audio/LocalSpeechModelStore.kt b/composeApp/src/jvmLocalMain/kotlin/com/vrcmc/app/audio/LocalSpeechModelStore.kt new file mode 100644 index 0000000..52ae935 --- /dev/null +++ b/composeApp/src/jvmLocalMain/kotlin/com/vrcmc/app/audio/LocalSpeechModelStore.kt @@ -0,0 +1,212 @@ +package com.vrcmc.app + +import io.ktor.client.plugins.HttpTimeout +import io.ktor.client.request.prepareGet +import io.ktor.client.statement.bodyAsChannel +import io.ktor.http.isSuccess +import io.ktor.utils.io.ByteReadChannel +import io.ktor.utils.io.readAvailable +import java.nio.file.AtomicMoveNotSupportedException +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardCopyOption +import java.security.MessageDigest +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive + +private const val senseVoiceTokensFileName = "tokens.txt" + +private data class LocalSpeechModelArtifact( + val fileName: String, + val size: Long, + val sha256: String, + val repository: String, + val revision: String, + val tokensSize: Long, + val tokensSha256: String, +) + +private fun LocalSpeechModel.artifact(): LocalSpeechModelArtifact = when (this) { + LocalSpeechModel.SENSE_VOICE_SMALL_INT8 -> LocalSpeechModelArtifact( + fileName = "model.int8.onnx", + size = 239_233_841L, + sha256 = "c71f0ce00bec95b07744e116345e33d8cbbe08cef896382cf907bf4b51a2cd51", + repository = "csukuangfj/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17", + revision = "2365baeacb507f821a0c8120fcee3d484dba7a07", + tokensSize = 315_894L, + tokensSha256 = "f449eb28dc567533d7fa59be34e2abca8784f771850c78a47fb731a31429a1dc", + ) + LocalSpeechModel.FUN_ASR_NANO_2512_INT8 -> LocalSpeechModelArtifact( + fileName = "model.int8.onnx", + size = 263_531_902L, + sha256 = "9dc6e72aa8bc6f5966cf2857a0ce3a425b1d72e91500e147d66329f407c017a1", + repository = "csukuangfj/sherpa-onnx-sense-voice-funasr-nano-int8-2025-12-17", + revision = "ebb95fbda2a034d9a8f3b2d2cba32c104b60bed3", + tokensSize = 939_815L, + tokensSha256 = "2db4bb25d046e8849e336c9465e248e1694914d996c58c71bdeca18cfb722992", + ) +} + +internal fun LocalSpeechModel.modelFileName(): String = artifact().fileName +internal fun LocalSpeechModel.modelSize(): Long = artifact().size +internal fun LocalSpeechModel.modelSha256(): String = artifact().sha256 + +// Call on Dispatchers.IO. A failed or cancelled download must never replace a valid model. +internal class LocalSpeechModelStore( + val path: Path, + internal val expectedSize: Long = LocalSpeechModel.SENSE_VOICE_SMALL_INT8.modelSize(), + private val expectedHash: String = LocalSpeechModel.SENSE_VOICE_SMALL_INT8.modelSha256(), + val auxiliaryPath: Path? = null, + private val expectedAuxiliarySize: Long = 0, + private val expectedAuxiliaryHash: String = "", +) { + internal val expectedTotalSize: Long + get() = expectedSize + if (auxiliaryPath != null) expectedAuxiliarySize else 0 + + suspend fun isValid(): Boolean = verifyFile(path, expectedSize, expectedHash) + + suspend fun isAuxiliaryValid(): Boolean { + val target = auxiliaryPath ?: return true + return verifyFile(target, expectedAuxiliarySize, expectedAuxiliaryHash) + } + + suspend fun isComplete(): Boolean = isValid() && isAuxiliaryValid() + + private suspend fun verifyFile(target: Path, expectedBytes: Long, expectedDigest: String): Boolean { + if (!Files.isRegularFile(target) || Files.size(target) != expectedBytes) return false + val digest = MessageDigest.getInstance("SHA-256") + Files.newInputStream(target).use { input -> + val buffer = ByteArray(64 * 1024) + while (true) { + currentCoroutineContext().ensureActive() + val count = input.read(buffer) + if (count < 0) break + digest.update(buffer, 0, count) + } + } + return digest.digest().toHexString() == expectedDigest + } + + suspend fun install(channel: ByteReadChannel, onProgress: (Long, Long) -> Unit) { + installFile(path, expectedSize, expectedHash, channel, onProgress) + } + + suspend fun installAuxiliary(channel: ByteReadChannel, onProgress: (Long, Long) -> Unit) { + val target = checkNotNull(auxiliaryPath) + installFile(target, expectedAuxiliarySize, expectedAuxiliaryHash, channel, onProgress) + } + + private suspend fun installFile( + target: Path, + expectedBytes: Long, + expectedDigest: String, + channel: ByteReadChannel, + onProgress: (Long, Long) -> Unit, + ) { + Files.createDirectories(target.toAbsolutePath().parent) + val temporary = Files.createTempFile(target.toAbsolutePath().parent, "${target.fileName}-", ".part") + try { + val digest = MessageDigest.getInstance("SHA-256") + var received = 0L + var reported = 0L + onProgress(0, expectedBytes) + Files.newOutputStream(temporary).use { output -> + val buffer = ByteArray(64 * 1024) + while (true) { + currentCoroutineContext().ensureActive() + val count = channel.readAvailable(buffer, 0, buffer.size) + if (count < 0) break + if (count == 0) continue + received += count + check(received <= expectedBytes) { "Model exceeds expected size" } + output.write(buffer, 0, count) + digest.update(buffer, 0, count) + if (received - reported >= 256 * 1024 || received == expectedBytes) { + onProgress(received, expectedBytes) + reported = received + } + } + } + check(received == expectedBytes) { "Incomplete model download: $received / $expectedBytes bytes" } + check(digest.digest().toHexString() == expectedDigest) { "Model checksum mismatch" } + currentCoroutineContext().ensureActive() + try { + Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) + } catch (_: AtomicMoveNotSupportedException) { + Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING) + } + } finally { + Files.deleteIfExists(temporary) + } + } +} + +internal fun LocalSpeechModel.createStore(path: Path): LocalSpeechModelStore = + LocalSpeechModelStore( + path = path, + expectedSize = modelSize(), + expectedHash = modelSha256(), + auxiliaryPath = path.resolveSibling(senseVoiceTokensFileName), + expectedAuxiliarySize = artifact().tokensSize, + expectedAuxiliaryHash = artifact().tokensSha256, + ) + +internal suspend fun downloadSpeechModel( + model: LocalSpeechModel, + store: LocalSpeechModelStore, + onProgress: (Long, Long) -> Unit, +) { + val client = createVrcmcHttpClient { + install(HttpTimeout) { + connectTimeoutMillis = 15_000 + socketTimeoutMillis = 60_000 + requestTimeoutMillis = 1_200_000 + } + } + try { + var lastFailure: Exception? = null + var modelValid = store.isValid() + var auxiliaryValid = store.isAuxiliaryValid() + if (modelValid && auxiliaryValid) return + val total = store.expectedTotalSize + val artifact = model.artifact() + // Both sources serve the same pinned files; SHA-256 is checked before they can be loaded. + for (host in listOf("huggingface.co", "hf-mirror.com")) { + try { + if (!modelValid) { + client.prepareGet( + "https://$host/${artifact.repository}/resolve/" + + "${artifact.revision}/${artifact.fileName}", + ).execute { response -> + check(response.status.isSuccess()) { "Model server returned HTTP ${response.status.value}" } + store.install(response.bodyAsChannel()) { received, _ -> + onProgress(received, total) + } + } + modelValid = true + } + if (!auxiliaryValid) { + client.prepareGet( + "https://$host/${artifact.repository}/resolve/" + + "${artifact.revision}/$senseVoiceTokensFileName", + ).execute { response -> + check(response.status.isSuccess()) { "Model server returned HTTP ${response.status.value}" } + store.installAuxiliary(response.bodyAsChannel()) { received, _ -> + onProgress(store.expectedSize + received, total) + } + } + auxiliaryValid = true + } + if (modelValid && auxiliaryValid) return + } catch (error: CancellationException) { + throw error + } catch (error: Exception) { + lastFailure = error + } + } + throw checkNotNull(lastFailure) + } finally { + client.close() + } +} diff --git a/composeApp/src/jvmLocalMain/kotlin/com/vrcmc/app/audio/SenseVoiceRecognition.kt b/composeApp/src/jvmLocalMain/kotlin/com/vrcmc/app/audio/SenseVoiceRecognition.kt new file mode 100644 index 0000000..0178c42 --- /dev/null +++ b/composeApp/src/jvmLocalMain/kotlin/com/vrcmc/app/audio/SenseVoiceRecognition.kt @@ -0,0 +1,330 @@ +package com.vrcmc.app + +import ai.onnxruntime.OnnxTensor +import ai.onnxruntime.OrtEnvironment +import ai.onnxruntime.OrtSession +import java.nio.FloatBuffer +import java.nio.IntBuffer +import java.nio.charset.StandardCharsets +import java.nio.file.Files +import java.nio.file.Path +import kotlin.math.PI +import kotlin.math.cos +import kotlin.math.ln +import kotlin.math.max +import kotlin.math.sin + +private const val senseVoiceSampleRate = 16_000 +private const val senseVoiceFrameLength = 400 +private const val senseVoiceFrameShift = 160 +private const val senseVoiceFftSize = 512 +internal const val localSpeechMelBins = 80 +private const val senseVoiceLowFrequency = 20.0 +private const val senseVoiceHighFrequency = 8_000.0 +private const val senseVoiceFftBinWidth = senseVoiceSampleRate.toDouble() / senseVoiceFftSize +private const val senseVoiceLogFloor = 1.1920929e-7 + +internal class SenseVoiceEngine(model: Path) : LocalSpeechEngine { + private val environment = OrtEnvironment.getEnvironment() + private val session = OrtSession.SessionOptions().use { options -> + options.setInterOpNumThreads(1) + options.setIntraOpNumThreads( + Runtime.getRuntime().availableProcessors().let { (it / 2).coerceIn(1, 6) }, + ) + environment.createSession(model.toString(), options) + } + private val metadata = session.metadata.customMetadata + private val lfrWindowSize = metadata.getValue("lfr_window_size").toInt() + private val lfrWindowShift = metadata.getValue("lfr_window_shift").toInt() + private val featureDimension = localSpeechMelBins * lfrWindowSize + private val negMean = parseSenseVoiceNumbers(metadata.getValue("neg_mean"), featureDimension) + private val invStddev = parseSenseVoiceNumbers(metadata.getValue("inv_stddev"), featureDimension) + private val tokens = Files.readAllLines( + model.resolveSibling("tokens.txt"), + StandardCharsets.UTF_8, + ).map { line -> line.substringBeforeLast(' ') } + private val melBanks = localSpeechMelBanks() + + override fun transcribe(samples: FloatArray, language: String): String { + val fbank = localSpeechFbank(samples, melBanks) + if (fbank.isEmpty()) return "" + val features = localSpeechApplyLfr(fbank, localSpeechMelBins, lfrWindowSize, lfrWindowShift) + applySenseVoiceCmvn(features, negMean, invStddev) + val frames = features.size / featureDimension + if (frames == 0) return "" + + val languageId = senseVoiceLanguageId(language) + val textNormId = metadata.getValue("with_itn").toInt() + val logits = try { + OnnxTensor.createTensor( + environment, + FloatBuffer.wrap(features), + longArrayOf(1, frames.toLong(), featureDimension.toLong()), + ).use { x -> + OnnxTensor.createTensor( + environment, + IntBuffer.wrap(intArrayOf(frames)), + longArrayOf(1), + ).use { xLength -> + OnnxTensor.createTensor( + environment, + IntBuffer.wrap(intArrayOf(languageId)), + longArrayOf(1), + ).use { languageTensor -> + OnnxTensor.createTensor( + environment, + IntBuffer.wrap(intArrayOf(textNormId)), + longArrayOf(1), + ).use { textNorm -> + session.run( + mapOf( + "x" to x, + "x_length" to xLength, + "language" to languageTensor, + "text_norm" to textNorm, + ), + ).use { result -> + val output = result.get("logits").orElseThrow() as OnnxTensor + val values = output.floatBuffer + val shape = output.info.shape + val copied = FloatArray(values.remaining()) + values.get(copied) + CtcLogits(copied, shape[1].toInt(), shape[2].toInt()) + } + } + } + } + } + } catch (error: Exception) { + throw IllegalStateException("SenseVoice inference failed", error) + } + return decodeCtcLogits( + logits.values, + logits.frames, + logits.vocabularySize, + tokens, + blankId = 0, + ) + } + + private fun senseVoiceLanguageId(language: String): Int { + val key = when (language.lowercase()) { + "zh" -> "lang_zh" + "en" -> "lang_en" + "yue" -> "lang_yue" + "ja" -> "lang_ja" + "ko" -> "lang_ko" + else -> "lang_auto" + } + return metadata.getValue(key).toInt() + } + + override fun close() = session.close() +} + +internal data class CtcLogits( + val values: FloatArray, + val frames: Int, + val vocabularySize: Int, +) + +internal fun localSpeechFbank( + samples: FloatArray, + melBanks: Array = localSpeechMelBanks(), +): FloatArray { + if (samples.size < senseVoiceFrameLength) return FloatArray(0) + val frames = 1 + (samples.size - senseVoiceFrameLength) / senseVoiceFrameShift + val features = FloatArray(frames * localSpeechMelBins) + val hamming = DoubleArray(senseVoiceFrameLength) { index -> + 0.54 - 0.46 * cos(2.0 * PI * index / (senseVoiceFrameLength - 1)) + } + val real = DoubleArray(senseVoiceFftSize) + val imaginary = DoubleArray(senseVoiceFftSize) + var output = 0 + for (frame in 0 until frames) { + val start = frame * senseVoiceFrameShift + var mean = 0.0 + for (index in 0 until senseVoiceFrameLength) { + real[index] = samples[start + index] * 32768.0 + mean += real[index] + } + mean /= senseVoiceFrameLength + for (index in 0 until senseVoiceFrameLength) real[index] -= mean + for (index in senseVoiceFrameLength - 1 downTo 1) { + real[index] -= 0.97 * real[index - 1] + } + real[0] -= 0.97 * real[0] + for (index in 0 until senseVoiceFrameLength) { + real[index] *= hamming[index] + imaginary[index] = 0.0 + } + for (index in senseVoiceFrameLength until senseVoiceFftSize) { + real[index] = 0.0 + imaginary[index] = 0.0 + } + fft(real, imaginary) + for (mel in 0 until localSpeechMelBins) { + var energy = 0.0 + for (bin in 0..senseVoiceFftSize / 2) { + val power = real[bin] * real[bin] + imaginary[bin] * imaginary[bin] + energy += melBanks[mel][bin] * power + } + features[output++] = ln(max(energy, senseVoiceLogFloor)).toFloat() + } + } + return features +} + +internal fun localSpeechApplyLfr( + input: FloatArray, + inputDimension: Int, + windowSize: Int, + windowShift: Int, +): FloatArray { + require(inputDimension > 0 && input.size % inputDimension == 0) + require(windowSize > 0 && windowShift > 0) + if (input.isEmpty()) return FloatArray(0) + val inputFrames = input.size / inputDimension + val outputFrames = 1 + (inputFrames - 1) / windowShift + val output = FloatArray(outputFrames * inputDimension * windowSize) + val leftContext = (windowSize - 1) / 2 + var destination = 0 + for (frame in 0 until outputFrames) { + val centerFrame = frame * windowShift + val leftPadding = if (centerFrame < leftContext) leftContext - centerFrame else 0 + val firstFrame = if (centerFrame < leftContext) 0 else centerFrame - leftContext + val maximumOffset = inputFrames - 1 - firstFrame + for (index in 0 until windowSize) { + val sourceFrame = if (index < leftPadding) { + 0 + } else { + val offset = index - leftPadding + if (offset > maximumOffset) inputFrames - 1 else firstFrame + offset + } + input.copyInto(output, destination, sourceFrame * inputDimension, (sourceFrame + 1) * inputDimension) + destination += inputDimension + } + } + return output +} + +internal fun decodeCtcLogits( + logits: FloatArray, + frames: Int, + vocabularySize: Int, + tokens: List, + blankId: Int, +): String { + require(logits.size >= frames * vocabularySize) + require(vocabularySize <= tokens.size) + val decoded = StringBuilder() + var previous = -1 + for (frame in 0 until frames) { + var best = 0 + var bestScore = Float.NEGATIVE_INFINITY + val offset = frame * vocabularySize + for (token in 0 until vocabularySize) { + val score = logits[offset + token] + if (score > bestScore) { + best = token + bestScore = score + } + } + if (best != blankId && best != previous) { + val symbol = tokens[best] + if ( + !symbol.startsWith("<|") && + symbol != "" && + symbol != "" && + symbol != "" && + symbol != "" + ) { + decoded.append(symbol.replace('\u2581', ' ')) + } + } + previous = best + } + return decoded.toString().replace(Regex(" +"), " ").trim() +} + +private fun applySenseVoiceCmvn(features: FloatArray, negMean: FloatArray, invStddev: FloatArray) { + val dimension = negMean.size + for (index in features.indices) { + val channel = index % dimension + features[index] = (features[index] + negMean[channel]) * invStddev[channel] + } +} + +private fun parseSenseVoiceNumbers(value: String, expectedSize: Int): FloatArray = + value.removePrefix("[").removeSuffix("]").split(',') + .map { it.trim().toFloat() } + .toFloatArray() + .also { require(it.size == expectedSize) { "Unexpected SenseVoice normalization size: ${it.size}" } } + +internal fun localSpeechMelBanks(): Array { + val melLow = senseVoiceMel(senseVoiceLowFrequency) + val melHigh = senseVoiceMel(senseVoiceHighFrequency) + val delta = (melHigh - melLow) / (localSpeechMelBins + 1) + return Array(localSpeechMelBins) { mel -> + val left = melLow + mel * delta + val center = melLow + (mel + 1) * delta + val right = melLow + (mel + 2) * delta + DoubleArray(senseVoiceFftSize / 2 + 1) { bin -> + val value = senseVoiceMel(bin * senseVoiceFftBinWidth) + when { + value <= left || value >= right -> 0.0 + value <= center -> (value - left) / (center - left) + else -> (right - value) / (right - center) + } + } + } +} + +private fun senseVoiceMel(frequency: Double): Double = 1127.0 * ln(1.0 + frequency / 700.0) + +private fun fft(real: DoubleArray, imaginary: DoubleArray) { + val size = real.size + var reversed = 0 + for (index in 1 until size) { + var bit = size shr 1 + while ((reversed and bit) != 0) { + reversed = reversed xor bit + bit = bit shr 1 + } + reversed = reversed xor bit + if (index < reversed) { + var value = real[index] + real[index] = real[reversed] + real[reversed] = value + value = imaginary[index] + imaginary[index] = imaginary[reversed] + imaginary[reversed] = value + } + } + var length = 2 + while (length <= size) { + val angle = -2.0 * PI / length + val stepReal = cos(angle) + val stepImaginary = sin(angle) + var offset = 0 + while (offset < size) { + var phaseReal = 1.0 + var phaseImaginary = 0.0 + for (index in 0 until length / 2) { + val even = offset + index + val odd = even + length / 2 + val oddReal = real[odd] * phaseReal - imaginary[odd] * phaseImaginary + val oddImaginary = real[odd] * phaseImaginary + imaginary[odd] * phaseReal + real[odd] = real[even] - oddReal + imaginary[odd] = imaginary[even] - oddImaginary + real[even] += oddReal + imaginary[even] += oddImaginary + val nextReal = phaseReal * stepReal - phaseImaginary * stepImaginary + phaseImaginary = phaseReal * stepImaginary + phaseImaginary * stepReal + phaseReal = nextReal + } + offset += length + } + length = length shl 1 + } +} diff --git a/composeApp/src/jvmLocalMain/kotlin/com/vrcmc/app/audio/SpeechPcm.kt b/composeApp/src/jvmLocalMain/kotlin/com/vrcmc/app/audio/SpeechPcm.kt new file mode 100644 index 0000000..e4da2e1 --- /dev/null +++ b/composeApp/src/jvmLocalMain/kotlin/com/vrcmc/app/audio/SpeechPcm.kt @@ -0,0 +1,88 @@ +package com.vrcmc.app + +import kotlin.math.roundToInt + +private data class Pcm16Wave( + val sampleRate: Int, + val channels: Int, + val samples: FloatArray, +) + +internal fun speechPcmSamples(wav: ByteArray): FloatArray { + require(wav.size >= 44 && ascii(wav, 0, 4) == "RIFF" && ascii(wav, 8, 4) == "WAVE") { + "Invalid WAV audio" + } + var offset = 12 + var channels = 0 + var sampleRate = 0 + var bitsPerSample = 0 + var formatCode = 0 + var dataOffset = -1 + var dataSize = 0 + while (offset + 8 <= wav.size) { + val id = ascii(wav, offset, 4) + val size = readUInt32(wav, offset + 4) + require(size <= Int.MAX_VALUE) { "WAV chunk is too large" } + val content = offset + 8 + require(content.toLong() + size <= wav.size) { "Truncated WAV chunk" } + when (id) { + "fmt " -> { + require(size >= 16) { "Invalid WAV format chunk" } + formatCode = readUInt16(wav, content) + channels = readUInt16(wav, content + 2) + sampleRate = readUInt32(wav, content + 4).toInt() + bitsPerSample = readUInt16(wav, content + 14) + } + "data" -> { + dataOffset = content + dataSize = size.toInt() + } + } + offset = content + size.toInt() + (size.toInt() and 1) + } + require(formatCode == 1) { "Only PCM WAV audio is supported" } + require(channels in 1..2) { "Unsupported WAV channel count: $channels" } + require(sampleRate > 0) { "Invalid WAV sample rate" } + require(bitsPerSample == 16) { "Only PCM16 WAV audio is supported" } + require(dataOffset >= 0) { "WAV audio has no data chunk" } + + val frameSize = channels * 2 + val frames = dataSize / frameSize + require(frames > 0) { "Invalid PCM audio" } + val monoSamples = FloatArray(frames) { frame -> + var sum = 0 + for (channel in 0 until channels) { + val sampleOffset = dataOffset + frame * frameSize + channel * 2 + val low = wav[sampleOffset].toInt() and 0xff + val high = wav[sampleOffset + 1].toInt() + sum += (high shl 8) or low + } + (sum.toFloat() / channels) / 32768f + } + return resampleTo16Khz(monoSamples, sampleRate) +} + +private fun resampleTo16Khz(samples: FloatArray, sampleRate: Int): FloatArray { + if (sampleRate == 16_000) return samples + val outputSize = (samples.size.toLong() * 16_000L / sampleRate).toInt() + require(outputSize > 0) { "Audio is too short" } + return FloatArray(outputSize) { index -> + val position = index.toDouble() * sampleRate / 16_000.0 + val left = position.toInt().coerceIn(0, samples.lastIndex) + val right = (left + 1).coerceAtMost(samples.lastIndex) + val fraction = (position - left).toFloat() + samples[left] + (samples[right] - samples[left]) * fraction + } +} + +private fun ascii(bytes: ByteArray, offset: Int, length: Int): String = + bytes.copyOfRange(offset, offset + length).decodeToString() + +private fun readUInt16(bytes: ByteArray, offset: Int): Int = + (bytes[offset].toInt() and 0xff) or ((bytes[offset + 1].toInt() and 0xff) shl 8) + +private fun readUInt32(bytes: ByteArray, offset: Int): Long = + (bytes[offset].toLong() and 0xff) or + ((bytes[offset + 1].toLong() and 0xff) shl 8) or + ((bytes[offset + 2].toLong() and 0xff) shl 16) or + ((bytes[offset + 3].toLong() and 0xff) shl 24) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 148f93e..46c9b42 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -14,10 +14,8 @@ kuromoji = "0.9.0" wanakana = "1.1.1" onnxruntime = "1.20.0" lwjgl = "3.3.6" -whisper-jni = "1.7.1" [libraries] -whisper-jni = { module = "io.github.givimad:whisper-jni", version.ref = "whisper-jni" } lwjgl-core = { module = "org.lwjgl:lwjgl", version.ref = "lwjgl" } lwjgl-openvr = { module = "org.lwjgl:lwjgl-openvr", version.ref = "lwjgl" } lwjgl-opengl = { module = "org.lwjgl:lwjgl-opengl", version.ref = "lwjgl" } diff --git a/scripts/download-local-asr-fixtures.py b/scripts/download-local-asr-fixtures.py deleted file mode 100644 index 91df91e..0000000 --- a/scripts/download-local-asr-fixtures.py +++ /dev/null @@ -1,57 +0,0 @@ -"""Download three deterministic human recordings per language for opt-in ASR QA. - -FLEURS is CC-BY-4.0: https://huggingface.co/datasets/google/fleurs -Only the first three WAV members of each test archive are streamed; archives -are never extracted to disk. Audio and the manifest stay in the ignored build/. -Requires requests (pip install requests). -""" -import csv -import io -import json -from pathlib import Path -import tarfile - -import requests - -REVISION = "70bb2e84b976b7e960aa89f1c648e09c59f894dd" -ROOT = Path(__file__).resolve().parents[1] / "composeApp/build/local-asr-test/fleurs" -BASE = f"https://hf-mirror.com/datasets/google/fleurs/resolve/{REVISION}/data" - - -def main(): - ROOT.mkdir(parents=True, exist_ok=True) - manifest = [] - for language, config in [("zh", "cmn_hans_cn"), ("ja", "ja_jp"), ("en", "en_us")]: - index = requests.get(f"{BASE}/{config}/test.tsv", timeout=(15, 60)) - index.raise_for_status() - records = {row[1]: row for row in csv.reader(io.StringIO(index.text), delimiter="\t")} - selected = [] - with requests.get(f"{BASE}/{config}/audio/test.tar.gz", stream=True, timeout=(15, 60)) as response: - response.raise_for_status() - with tarfile.open(fileobj=response.raw, mode="r|gz") as archive: - for member in archive: - name = Path(member.name).name - if not member.isfile() or name not in records: - continue - if not name.endswith(".wav") or member.size > 10_000_000: - continue - row = records[name] - destination = f"{language}-{name}" - with archive.extractfile(member) as audio: - (ROOT / destination).write_bytes(audio.read()) - selected.append({ - "language": language, "file": destination, "text": row[2], - "gender": row[6], "dataset": "google/fleurs", "config": config, - "revision": REVISION, "license": "CC-BY-4.0", - }) - if len(selected) == 3: - break - if len(selected) != 3: - raise RuntimeError(f"Could not retrieve three recordings for {config}") - manifest.extend(selected) - print(f"{language}: downloaded {len(selected)} FLEURS recordings", flush=True) - (ROOT / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8") - - -if __name__ == "__main__": - main()