diff --git a/CLAUDE.md b/CLAUDE.md
index 6099955..8f5a549 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -7,7 +7,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
**Exolobe** — macOS 向けの Web 会議録音アプリ(Electron + React + TypeScript)。録音・文字起こし・
話者識別・要約をすべてローカルで実行し、音声もテキストも外部に送信しない。
詳細な背景は `README.md` と `docs/`(`architecture.html` / `specification.html` /
-`decisions.html` = ADR-001〜048)にある。**設計の「なぜ」を変える変更をする前に
+`decisions.html` = ADR-001〜049)にある。**設計の「なぜ」を変える変更をする前に
`docs/decisions.html` の該当 ADR を読むこと。**
## コマンド
@@ -246,6 +246,14 @@ IPC ハンドラは `src/main/ipc/handlers.ts`、公開は `src/preload/index.ts
判定しない(`settings.json` は全体を保存するので、既定の文面を直すと触っていない人まで「書き換えた」ことになる)。
既定の本文は画面で編集させず、既定の文面は `DEFAULT_SUMMARY_PROMPT(_EN)` を書き換えれば全員に届く。
`isDefaultSummaryPrompt` は `promptMode` を持たない前の設定の読み替えにだけ使う。
+- 文字起こしのエンジンに Haas-ja-v1.0 を選べる(ADR-049)が、**既定は whisper のまま**にする。公式の重みは NVIDIA GPU
+ 専用なので、有志の量子化版を `sherpa-onnx-node` の `nemo_transducer` で読む。変換版は TDT であることを encoder の
+ メタデータで伝え、予測ネットワーク(KDA)の状態を LSTM の形に詰めて渡している — **sherpa-onnx-node を上げたら、
+ `OMR_HAAS_MODEL_DIR` を付けて `tests/infrastructure/haas-session.test.ts` を走らせる**(無いと skip される)。
+ Haas は**会議の言語が `ja` のときだけ**使い(`transcriptionEngineOf`)、`auto` / `en` は whisper に任せる。
+ VAD は設定に関わらず常に掛け、喋っている区間だけを前後 0.25 秒の余白つきで認識する(無音や BGM から文を作らせない。
+ 余白が無いと語頭が削れて聞き違える)。確信度の下限 -1 と除外語「む」「むぅ」は公開コーパスの分布で決めた。トークンは
+ byte fallback(`<0xE6>`)で届くことがあるので、文を組み立てる側で UTF-8 に戻す。用語集は効かない。
- 取り込める拡張子は**変換器ごとに** `src/domain/AudioImport.ts` に持ち(afconvert / Media Foundation)、デコーダと組で
`src/main/audioConverters.ts` が OS に応じて選ぶ。一覧を変えたら、実機でその形式を変換して確かめる(ADR-048)。
- 取り込んだ音声は**全体を相手側(remote)として扱う**。自分の声を推定して `self` に割り当てると、
diff --git a/docs/decisions.html b/docs/decisions.html
index fe26023..5536852 100644
--- a/docs/decisions.html
+++ b/docs/decisions.html
@@ -81,6 +81,7 @@
一覧
| ADR-046 | 要約のモデルに Apple Intelligence を選べる | 既定は Gemma のまま。macOS 27 以降で、精度が劣ることを見せたうえで選んだ人だけが使う。分割・統合は共用し、同梱の applelm が 1 回ずつ応答する |
| ADR-047 | 要約プロンプトの既定とカスタム | 既定を使うかカスタムを使うかを promptMode で持ち、既定は全文を保存せず編集もさせない。アプリの更新で既定が変われば、触っていない人にはそのまま届く |
| ADR-048 | Windows 対応 | OS ごとに別のインストーラを作り、違いは結線(container)で実装を選んで吸収する。音声の変換は Media Foundation、補助プログラムは Rust。最初の版は x64・署名なし・カレンダー連携なし |
+ | ADR-049 | 文字起こしのエンジンに Haas-ja-v1.0 を選べる | 既定は whisper のまま。有志の量子化版を sherpa-onnx-node で動かし、VAD で切り出した発話区間だけを認識する。会議の言語が日本語のときだけ使う |
@@ -4508,6 +4509,116 @@ 残した判断
+ ADR-049 文字起こしのエンジンに Haas-ja-v1.0 を選べる(2026-11)
+
+
+
ADR-049
+
文字起こしのエンジンに Haas-ja-v1.0 を選べるようにする。既定は whisper のまま。有志の量子化版を sherpa-onnx-node で動かし、VAD で切り出した発話区間だけを認識する。会議の言語が日本語のときだけ使う
+
+
+
背景
+
+ Haas-ja-v1.0(third-intelligence、Apache-2.0)は Parakeet-TDT 系の日本語専用モデル(FastConformer + TDT、616M)で、
+ 予測ネットワークに Kimi Delta Attention(KDA)を使う。公開コーパスの人の声で測ると、whisper(large-v3-turbo + VAD)より
+ 文字誤り率が低かった(ReazonSpeech 100 発話で 12.5% → 4.3%、FLEURS で 5.8% → 4.7%。Common Voice は 10.0% → 1.2% だが学習データの重なりを疑う)。
+ 雑音・BGM・打鍵を挟んだ約 10 分の長尺でも、作り話は whisper と同じく 0 字だった。
+
+
+ 一方で公式の重み(.nemo)と推論コード(haas-asr)は Linux と NVIDIA GPU が前提で、KDA の核が Triton/CUDA にしか無く、
+ macOS では動かない。出力は句読点つきのテキストで、時刻と確信度は公式の口からは得られない。whisper と違い、
+ 無音や雑音の区間からも短い語を作ることがある(無音のクリップで「行くと。」、打鍵音の区間で「うん。」)。
+
+
+
決定
+
+ -
+ 有志の量子化版(oboroge0/Haas-ja-v1.0-onnx-quantized、約 480MB)を、話者識別と同じ
sherpa-onnx-node で動かす。
+ sherpa-onnx の nemo_transducer として読め、CPU で実時間の 25 倍ほど速い。新しいバイナリもランタイムも要らず、Windows でも動く。
+ 結果にトークンごとの時刻と対数確率が付くので、whisper と同じ形(区間ごとの文)で返せる。
+
+ -
+ VAD(sherpa-onnx の Silero、ONNX 形式)で切り出した発話区間だけを認識する。設定の「無音区間を文字起こししない」に関わらず常に使う。
+ 無音・BGM の区間はそもそも認識器に入らない。区間は 20 秒で切り(Haas は 30 秒前後の発話で学習されている)、前後に 0.25 秒の余白を足して渡す。
+ 余白が無いと VAD が遅れて検出した語頭が削れ、「ありがとうございます」が「視聴者ございます」、「三社に」が「生産者に」になった。
+ 余白は VAD が区間を分ける最短の無音(0.5 秒)の半分にとどめ、隣の区間の声を取り込まない。
+
+ -
+ 区間の認識結果は文末(句点)と 0.6 秒以上の間で文に分け、トークンの時刻から録音の時刻に戻す。
+ 語彙に無い字はバイトのトークン(
<0xE6>)で届くので、組み立てる側で UTF-8 に戻す(実機で「進捗」が化けた)。
+
+ -
+ テキストで判断する関門(非発話マーカー・動画の定型句・繰り返し)は whisper と共用し、確信度の下限は Haas の分布で決めた -1 にする。
+ 公開コーパスの人の声を文ごとに測ると、普通の文はどれも -0.53 より上で、下回ったのは息や雑音から出た「むぅ」「ん」のような 1〜3 字の断片だった
+ (本物の語は「この」の -0.84 だけ)。無音のクリップで VAD をすり抜けた区間から出た「下がり、」は -1.41。下限をすり抜けた「む」「むぅ」は定型句として落とす。
+
+ -
+ 会議の言語が日本語のときだけ使う。言語が
en や auto の録音は whisper で起こす(auto は UI が日本語でも英語の会議がありうる)。
+ 設定画面には、Haas を選んでいる間ずっと、日本語専用であること・用語集が効かないこと・VAD を常に使うことを出す。
+
+ -
+ 既定は whisper のまま。Haas のモデルは任意のパッケージ(5 ファイルと VAD をまとめて取得)にし、選んだ人だけが取得する。
+
+
+
+
選択肢
+
+
+ | 論点 | 案 | 判定 | 理由 |
+
+
+ | 動かし方 |
+ 公式の重みを NeMo で動かす |
+ 不採用 |
+ Linux と NVIDIA GPU が要り、macOS では動かない。Python の同梱も要る |
+
+
+ | 動かし方 |
+ speech.cpp の GGUF 版(Metal / Vulkan、時刻と VAD を持つ CLI) |
+ 不採用 |
+ 速く時刻も出せるが、whisper-cli と同じく新しいバイナリを両 OS 向けにビルドして同梱する手間が増える。sherpa-onnx-node は既に同梱している |
+
+
+ | 動かし方 |
+ MLX 版 / Core ML 版 |
+ 不採用 |
+ Apple Silicon 専用で Windows に使えない。MLX 版は Python が要る |
+
+
+ | 重み |
+ 量子化していない fp32 版(約 2.4GB) |
+ 不採用 |
+ 誤り率は量子化版と差が無く(公開コーパスで 3.8% と 3.6%)、メモリは約 3 倍使う |
+
+
+ | 無音・BGM の対策 |
+ 録音を丸ごと渡し、出力の文を除外語で落とす |
+ 不採用 |
+ 作り話の語に決まった形が無く(「行くと」「下がり」)、一覧では捕まえられない。長い音声を一度に渡すとメモリも伸びる |
+
+
+ | 用語集 |
+ sherpa-onnx の hotwords で効かせる |
+ 見送り |
+ modified_beam_search でしか効かず、TDT と変換版の組み合わせで動くか確かめていない |
+
+
+
+
+
+
残した判断
+
+ - 変換版は、TDT であることを encoder のメタデータ(
url の #tdt)で sherpa-onnx に伝え、KDA の状態を LSTM の形のテンソルに詰めて渡している。
+ どちらも sherpa-onnx の内部の挙動に頼るので、sherpa-onnx-node を上げたら OMR_HAAS_MODEL_DIR を付けて
+ tests/infrastructure/haas-session.test.ts を走らせる(モデルが無いと skip される。CI では走らない)。
+ - 確信度の下限と「む」「むぅ」は、公開コーパスと合成音声で決めた。実際の会議(遠いマイク・相手の圧縮音声・BGM)で外れていないかは、
+
OMR_LOG_DROPPED_SEGMENTS=1 で落とした文を見て確かめる。
+ - アプリの評価(
npm run eval:transcription)の合成音声では、Haas と whisper の差は表記の揺れ(「三社」と「3社」、「インデックス」と「index」)の範囲で、
+ どちらも作り話は 0 字だった。say の声は人の声より Haas に不利に出るので、エンジンの比較には公開コーパスの結果を使う。
+ - Haas はフィラー(「えー」「あの」)を省きがちで、出力の文体も指定できない(モデルカード)。文頭の「はい」が落ちることがある。
+ - メモリの見積もり(ADR-024)は whisper と同じ式に Haas の重みの大きさを入れている(約 1.2GB)。変換版の作者の実測(20 秒前後の区間で RSS 約 1GB)より大きめ。
+
+
+
今後見直す可能性がある判断
@@ -4653,6 +4764,14 @@ 今後見直す可能性がある判断
ADR-048 Windows は x64・署名なし・Vulkan のみ |
ARM64 の Windows の利用者が出たとき。SmartScreen の警告で配布に困ったとき。Vulkan で速さが足りないと分かったとき |
+
+ | ADR-049 Haas は有志の変換版を sherpa-onnx-node で動かす |
+ sherpa-onnx-node を上げて変換版が読めなくなったとき。公式が ONNX や macOS で動く形を出したとき。速さが足りず speech.cpp(Metal)に移す価値が出たとき |
+
+
+ | ADR-049 Haas の確信度の下限 -1 と定型句「む」「むぅ」 |
+ 実録音の計測モードで、本物の発言が落ちている、または作り話が残っていると分かったとき |
+
| arm64 のみのビルド |
Intel Mac の利用者が出たとき。whisper-cli をホスト依存でビルドしているため CI にジョブ追加が要る |
diff --git a/src/application/usecases/ProcessRecording.ts b/src/application/usecases/ProcessRecording.ts
index 038856b..7468473 100644
--- a/src/application/usecases/ProcessRecording.ts
+++ b/src/application/usecases/ProcessRecording.ts
@@ -36,7 +36,7 @@ import {
} from '@domain/MemoryGuard'
import { findAsset } from '@domain/ModelCatalog'
import { meetingLanguageOf, type MeetingLanguage } from '@domain/MeetingLanguage'
-import { summarizationProviderOf, summaryPromptFor, type Settings } from '@domain/Settings'
+import { summarizationProviderOf, summaryPromptFor, transcriptionEngineOf, type Settings } from '@domain/Settings'
import {
REMOTE_SPEAKER_ID,
SELF_SPEAKER_ID,
@@ -253,7 +253,10 @@ export class ProcessRecording {
private async demandOf(step: PipelineStep, settings: Settings): Promise {
switch (step) {
case 'transcribe': {
- const modelFileBytes = await this.modelBytes(settings.transcription.modelPath, 'transcription-model')
+ const modelFileBytes =
+ transcriptionEngineOf(settings) === 'haas-ja'
+ ? haasModelBytes(settings)
+ : await this.modelBytes(settings.transcription.modelPath, 'transcription-model')
if (modelFileBytes === undefined) return undefined
return {
bytes: estimateTranscriptionBytes({ modelFileBytes }),
@@ -542,3 +545,13 @@ const buildSpeakers = (
return speakers
}
+
+/**
+ * Haas の重みの大きさ。encoder.data は encoder が隣から読むので設定にパスが無く、カタログの値で数える。
+ * 変換版の実測(20 秒前後の区間で RSS 約 1GB)は、whisper と同じ見積もりの式で安全側に収まる(ADR-049)。
+ */
+const haasModelBytes = (settings: Settings): number | undefined => {
+ if (!settings.transcription.haasEncoderPath) return undefined
+ const ids = ['haas-encoder', 'haas-encoder-data', 'haas-decoder', 'haas-joiner']
+ return ids.reduce((sum, id) => sum + (findAsset(id)?.bytes ?? 0), 0)
+}
diff --git a/src/application/usecases/models.ts b/src/application/usecases/models.ts
index 0a15058..b4593b7 100644
--- a/src/application/usecases/models.ts
+++ b/src/application/usecases/models.ts
@@ -266,5 +266,18 @@ const configuredPath = (settings: Settings, id: ManagedAssetId): string => {
return settings.diarization.embeddingModelPath
case 'search-model':
return settings.search.modelPath
+ case 'haas-encoder':
+ return settings.transcription.haasEncoderPath
+ // encoder が隣から読むので、設定に対応する項目が無い。
+ case 'haas-encoder-data':
+ return ''
+ case 'haas-decoder':
+ return settings.transcription.haasDecoderPath
+ case 'haas-joiner':
+ return settings.transcription.haasJoinerPath
+ case 'haas-tokens':
+ return settings.transcription.haasTokensPath
+ case 'haas-vad':
+ return settings.transcription.haasVadModelPath
}
}
diff --git a/src/domain/ModelCatalog.ts b/src/domain/ModelCatalog.ts
index 0944292..5688999 100644
--- a/src/domain/ModelCatalog.ts
+++ b/src/domain/ModelCatalog.ts
@@ -19,6 +19,12 @@ export type ManagedAssetId =
| 'diarization-segmentation'
| 'diarization-embedding'
| 'search-model'
+ | 'haas-encoder'
+ | 'haas-encoder-data'
+ | 'haas-decoder'
+ | 'haas-joiner'
+ | 'haas-tokens'
+ | 'haas-vad'
export interface ManagedAsset {
readonly id: ManagedAssetId
@@ -134,6 +140,72 @@ export const MANAGED_ASSETS: readonly ManagedAsset[] = [
sha256: 'aa473d51f451a22f0fcf39ba3330c14bed38a385712b1113440f69df4047a173',
optional: true,
applyTo: (path) => ({ search: { modelPath: path } })
+ },
+ /**
+ * Haas-ja-v1.0 を文字起こしの別の選択肢にする(ADR-049)。
+ *
+ * 公式の重み(.nemo)は NVIDIA GPU と Triton が要り macOS で動かないので、sherpa-onnx の
+ * `nemo_transducer` で読める有志の量子化版を使う(Apache-2.0。CER は元の重みと差が無いと報告されている)。
+ * encoder.quantized.onnx は重みを隣の encoder.data から相対名で読むため、同じディレクトリに元の名前で置く。
+ */
+ {
+ id: 'haas-encoder',
+ url: 'https://huggingface.co/oboroge0/Haas-ja-v1.0-onnx-quantized/resolve/7f5ab0a4b1bf39db78afd6691eeecbc4f9d42e39/encoder.quantized.onnx',
+ fileName: 'haas-ja-v1.0/encoder.quantized.onnx',
+ bytes: 42_261_252,
+ sha256: 'aba291d61d3d594bc6fb8c7f90acbd980e7bc7bf6b7caaf3965ddc25e6f42fac',
+ optional: true,
+ applyTo: (path) => ({ transcription: { haasEncoderPath: path } })
+ },
+ {
+ id: 'haas-encoder-data',
+ url: 'https://huggingface.co/oboroge0/Haas-ja-v1.0-onnx-quantized/resolve/7f5ab0a4b1bf39db78afd6691eeecbc4f9d42e39/encoder.data',
+ fileName: 'haas-ja-v1.0/encoder.data',
+ bytes: 410_744_064,
+ sha256: '30befbf6aeb75383e6551f5e58de53efdb76972ddc7d0f76070c517899873586',
+ optional: true,
+ // encoder が自分で読むので、設定に書く項目が無い。
+ applyTo: () => ({})
+ },
+ {
+ id: 'haas-decoder',
+ url: 'https://huggingface.co/oboroge0/Haas-ja-v1.0-onnx-quantized/resolve/7f5ab0a4b1bf39db78afd6691eeecbc4f9d42e39/decoder.onnx',
+ fileName: 'haas-ja-v1.0/decoder.onnx',
+ bytes: 15_661_602,
+ sha256: '2947cb5512699cbba753fe45fe221428aadaa9856597debbb7aabe19cc253622',
+ optional: true,
+ applyTo: (path) => ({ transcription: { haasDecoderPath: path } })
+ },
+ {
+ id: 'haas-joiner',
+ url: 'https://huggingface.co/oboroge0/Haas-ja-v1.0-onnx-quantized/resolve/7f5ab0a4b1bf39db78afd6691eeecbc4f9d42e39/joiner.onnx',
+ fileName: 'haas-ja-v1.0/joiner.onnx',
+ bytes: 12_158_641,
+ sha256: '8a68320e750890ff9e944a794b41ae1c42c6f439ac4c273503458a6b42adc12d',
+ optional: true,
+ applyTo: (path) => ({ transcription: { haasJoinerPath: path } })
+ },
+ {
+ id: 'haas-tokens',
+ url: 'https://huggingface.co/oboroge0/Haas-ja-v1.0-onnx-quantized/resolve/7f5ab0a4b1bf39db78afd6691eeecbc4f9d42e39/tokens.txt',
+ fileName: 'haas-ja-v1.0/tokens.txt',
+ bytes: 28_704,
+ sha256: 'ec78b13c5d9f156cf0d5fdbd6b5aec5785680f319c92630c11d5d11b14b83a84',
+ optional: true,
+ applyTo: (path) => ({ transcription: { haasTokensPath: path } })
+ },
+ /**
+ * sherpa-onnx の VAD は ONNX 形式の Silero を読む。whisper 用の ggml 形式(vad-model)は使えない。
+ * Haas は無音や BGM から文を作りうるので、Haas と組でしか取得させない。
+ */
+ {
+ id: 'haas-vad',
+ url: 'https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/silero_vad.onnx',
+ fileName: 'silero_vad.onnx',
+ bytes: 643_854,
+ sha256: '9e2449e1087496d8d4caba907f23e0bd3f78d91fa552479bb9c23ac09cbb1fd6',
+ optional: true,
+ applyTo: (path) => ({ transcription: { haasVadModelPath: path } })
}
]
@@ -172,19 +244,30 @@ const assetOf = (id: ManagedAssetId): ManagedAsset => {
* 声紋の取り出しも両方が揃ったときだけ有効にしている。片方だけ取得・削除できても
* 何も動かず、どちらが欠けているのかを利用者に考えさせるだけになる。
*/
-const diarization = [assetOf('diarization-segmentation'), assetOf('diarization-embedding')]
+const bundle = (id: string, ids: readonly ManagedAssetId[]): ModelPackage => {
+ const assets = ids.map(assetOf)
+ return {
+ id,
+ optional: assets.every((asset) => asset.optional),
+ bytes: assets.reduce((sum, file) => sum + file.bytes, 0),
+ assets
+ }
+}
+
+/**
+ * Haas の 5 ファイルと VAD をまとめる理由も同じ。どれが欠けても認識器が作れず、
+ * VAD 無しで動かすと無音や BGM から文が生まれる(ADR-049)。
+ */
+const BUNDLES: readonly ModelPackage[] = [
+ bundle('diarization', ['diarization-segmentation', 'diarization-embedding']),
+ bundle('haas-ja', ['haas-encoder', 'haas-encoder-data', 'haas-decoder', 'haas-joiner', 'haas-tokens', 'haas-vad'])
+]
+/** 束ねたパッケージは、先頭のファイルがあった位置に置く(一覧の並びを変えない)。 */
export const MODEL_PACKAGES: readonly ModelPackage[] = MANAGED_ASSETS.flatMap((asset): ModelPackage[] => {
- if (asset.id === 'diarization-embedding') return []
- if (asset.id !== 'diarization-segmentation') return [single(asset)]
- return [
- {
- id: 'diarization',
- optional: true,
- bytes: diarization.reduce((sum, file) => sum + file.bytes, 0),
- assets: diarization
- }
- ]
+ const owner = BUNDLES.find((pkg) => pkg.assets.some((file) => file.id === asset.id))
+ if (owner === undefined) return [single(asset)]
+ return owner.assets[0]?.id === asset.id ? [owner] : []
})
/** 実行している環境で使えるもの。domain は OS を知らないので、結線が環境の能力として渡す。 */
diff --git a/src/domain/Settings.ts b/src/domain/Settings.ts
index c1931ce..1f32fd2 100644
--- a/src/domain/Settings.ts
+++ b/src/domain/Settings.ts
@@ -124,9 +124,21 @@ export const customSummaryPromptSeed = (settings: Settings, uiLanguage: MeetingL
*/
export const DEFAULT_CLUSTERING_THRESHOLD = 0.5
+/**
+ * 文字起こしに使うエンジン(ADR-049)。
+ *
+ * `whisper-cpp` は同梱の whisper-cli(large-v3-turbo)。`haas-ja` は Haas-ja-v1.0 を
+ * sherpa-onnx-node で動かす。Haas は日本語専用なので、使うかどうかは `transcriptionEngineOf` が言語も見て決める。
+ */
+export type TranscriptionProvider = 'whisper-cpp' | 'haas-ja'
+
+export const TRANSCRIPTION_PROVIDERS: readonly TranscriptionProvider[] = ['whisper-cpp', 'haas-ja']
+
+const isTranscriptionProvider = (value: unknown): value is TranscriptionProvider =>
+ TRANSCRIPTION_PROVIDERS.includes(value as TranscriptionProvider)
+
export interface TranscriptionSettings {
- /** 差し替え可能にするための識別子。将来クラウド実装を足す際の分岐キー。 */
- readonly provider: 'whisper-cpp'
+ readonly provider: TranscriptionProvider
readonly binaryPath: string
readonly modelPath: string
/** whisper に渡す言語コード。`auto` で自動判定。 */
@@ -148,6 +160,19 @@ export interface TranscriptionSettings {
* 変換の規則は `@domain/Glossary`。
*/
readonly glossary: readonly string[]
+ /**
+ * Haas-ja-v1.0(sherpa-onnx 形式)の 4 ファイル。未取得なら空文字。
+ * encoder は隣の encoder.data を相対名で読むので、同じディレクトリに置かれている前提。
+ */
+ readonly haasEncoderPath: string
+ readonly haasDecoderPath: string
+ readonly haasJoinerPath: string
+ readonly haasTokensPath: string
+ /**
+ * Haas の前に掛ける VAD(ONNX 形式の Silero)。whisper 用の ggml 形式とは別のファイル。
+ * Haas は無音や BGM から文を作りうるので、`vadEnabled` に関わらず常に使う。
+ */
+ readonly haasVadModelPath: string
}
/**
@@ -300,6 +325,21 @@ export const updateCheckIntervalOf = (settings: Settings): UpdateCheckInterval =
export const summarizationProviderOf = (settings: Settings): SummarizationProvider =>
isSummarizationProvider(settings.summarization.provider) ? settings.summarization.provider : 'llama-cpp'
+/** 設定で選ばれている文字起こしのエンジン。知らない値(新しい版が足したもの)なら既定の whisper に倒す。 */
+export const transcriptionProviderOf = (settings: Settings): TranscriptionProvider =>
+ isTranscriptionProvider(settings.transcription.provider) ? settings.transcription.provider : 'whisper-cpp'
+
+/**
+ * 実際に文字起こしに使うエンジン。
+ *
+ * Haas は日本語でしか学習していないので、会議の言語が日本語と決まっているときだけ使う。
+ * `auto` は録音ごとに言語を判定する設定で、UI が日本語でも英語の会議はありうるため whisper に任せる。
+ */
+export const transcriptionEngineOf = (settings: Settings): TranscriptionProvider =>
+ transcriptionProviderOf(settings) === 'haas-ja' && settings.transcription.language === 'ja'
+ ? 'haas-ja'
+ : 'whisper-cpp'
+
export interface Settings {
/** ユーザーが初期設定で選ぶ保存先。未選択なら null。 */
readonly storageDir: string | null
@@ -368,7 +408,12 @@ export const defaultSettings = (language: MeetingLanguage): Settings => ({
language,
vadEnabled: true,
vadModelPath: '',
- glossary: []
+ glossary: [],
+ haasEncoderPath: '',
+ haasDecoderPath: '',
+ haasJoinerPath: '',
+ haasTokensPath: '',
+ haasVadModelPath: ''
},
summarization: {
provider: 'llama-cpp',
@@ -449,6 +494,7 @@ export const validateSettings = (settings: Settings): SettingsProblem[] => {
if (!isUpdateCheckInterval(settings.updateCheck)) problems.push('updateCheck')
if (!isMemoryProtection(settings.memoryProtection)) problems.push('memoryProtection')
if (settings.summarization.contextSize < 1_024) problems.push('contextSize')
+ if (!isTranscriptionProvider(settings.transcription.provider)) problems.push('transcriptionProvider')
if (!isSummarizationProvider(settings.summarization.provider)) {
problems.push('summarizationProvider')
}
diff --git a/src/domain/ThirdPartyNotices.ts b/src/domain/ThirdPartyNotices.ts
index 1993fed..4aafe40 100644
--- a/src/domain/ThirdPartyNotices.ts
+++ b/src/domain/ThirdPartyNotices.ts
@@ -28,6 +28,7 @@ export type NoticeNoteId =
| 'systemAudioNoCopyright'
| 'ggmlConversionByWhisperCpp'
| 'onnxConversionBySherpa'
+ | 'onnxConversionByOboroge0'
| 'ggufConversionByGgmlOrg'
export interface ThirdPartyNotice {
@@ -149,7 +150,14 @@ const MODELS: readonly ThirdPartyNotice[] = [
license: 'MIT',
url: 'https://github.com/snakers4/silero-vad',
copyright: 'Copyright (c) 2020-present Silero Team',
- assetIds: ['vad-model']
+ assetIds: ['vad-model', 'haas-vad']
+ },
+ {
+ name: 'Haas-ja-v1.0',
+ license: 'Apache-2.0',
+ url: 'https://huggingface.co/third-intelligence/Haas-ja-v1.0',
+ noteId: 'onnxConversionByOboroge0',
+ assetIds: ['haas-encoder', 'haas-encoder-data', 'haas-decoder', 'haas-joiner', 'haas-tokens']
},
{
name: 'Gemma',
diff --git a/src/domain/errors.ts b/src/domain/errors.ts
index 98ebcbc..31d5f32 100644
--- a/src/domain/errors.ts
+++ b/src/domain/errors.ts
@@ -17,6 +17,7 @@ export type SettingsProblem =
| 'updateCheck'
| 'memoryProtection'
| 'contextSize'
+ | 'transcriptionProvider'
| 'summarizationProvider'
| 'promptPlaceholder'
| 'chatMaxRecordings'
@@ -80,6 +81,7 @@ export type ErrorReason =
| { readonly code: 'wavClosed' }
| { readonly code: 'encodeFailed'; readonly detail: string }
| { readonly code: 'transcriptionModelNotConfigured' }
+ | { readonly code: 'haasModelNotConfigured' }
| { readonly code: 'transcriptionOutputUnreadable' }
| { readonly code: 'whisperNotFound'; readonly binaryPath: string }
| { readonly code: 'whisperModelLoadFailed' }
diff --git a/src/infrastructure/diarization/sherpaModule.ts b/src/infrastructure/diarization/sherpaModule.ts
index 4c0fbee..297421a 100644
--- a/src/infrastructure/diarization/sherpaModule.ts
+++ b/src/infrastructure/diarization/sherpaModule.ts
@@ -5,13 +5,16 @@ import { toMessage, type ErrorReason, type SherpaModel } from '@domain/errors'
/**
* sherpa-onnx-node(ネイティブアドオン)の読み込み口。
*
- * 話者分割と声紋抽出の両方が同じモジュールを使うので、CJS の癖とモデルの
+ * 話者分割・声紋抽出・Haas の文字起こしが同じモジュールを使うので、CJS の癖とモデルの
* 存在確認をここ 1 か所にまとめる。WASM 版から乗り換えた経緯は ADR-028。
*/
export interface SherpaExports {
OfflineSpeakerDiarization: typeof import('sherpa-onnx-node').OfflineSpeakerDiarization
SpeakerEmbeddingExtractor: typeof import('sherpa-onnx-node').SpeakerEmbeddingExtractor
+ OfflineRecognizer: typeof import('sherpa-onnx-node').OfflineRecognizer
+ Vad: typeof import('sherpa-onnx-node').Vad
+ LinearResampler: typeof import('sherpa-onnx-node').LinearResampler
}
/** import() が返した名前空間。名前付き export はある場合と無い場合がある。 */
@@ -24,7 +27,10 @@ export type SherpaNamespace = Partial & { default: SherpaExports
*/
export const pickSherpaExports = (namespace: SherpaNamespace): SherpaExports => ({
OfflineSpeakerDiarization: namespace.OfflineSpeakerDiarization ?? namespace.default.OfflineSpeakerDiarization,
- SpeakerEmbeddingExtractor: namespace.SpeakerEmbeddingExtractor ?? namespace.default.SpeakerEmbeddingExtractor
+ SpeakerEmbeddingExtractor: namespace.SpeakerEmbeddingExtractor ?? namespace.default.SpeakerEmbeddingExtractor,
+ OfflineRecognizer: namespace.OfflineRecognizer ?? namespace.default.OfflineRecognizer,
+ Vad: namespace.Vad ?? namespace.default.Vad,
+ LinearResampler: namespace.LinearResampler ?? namespace.default.LinearResampler
})
/**
diff --git a/src/infrastructure/transcription/SherpaHaasSessionFactory.ts b/src/infrastructure/transcription/SherpaHaasSessionFactory.ts
new file mode 100644
index 0000000..930177d
--- /dev/null
+++ b/src/infrastructure/transcription/SherpaHaasSessionFactory.ts
@@ -0,0 +1,104 @@
+import { existsSync } from 'node:fs'
+import { loadSherpa, sherpaThreads } from '@infrastructure/diarization/sherpaModule'
+import type { HaasModelPaths, HaasSession, HaasSessionFactory, HaasSpeechSpan } from './SherpaHaasTranscriber'
+import { TranscriptionError } from './WhisperCppTranscriber'
+
+/** Haas と Silero VAD が前提とするサンプルレート。 */
+const SAMPLE_RATE = 16_000
+
+/** Silero VAD が 1 回に読むサンプル数(16kHz のとき 512 が決まり)。 */
+const VAD_WINDOW = 512
+
+/**
+ * VAD の区切り方(ADR-049)。
+ *
+ * - minSilenceDuration: 息継ぎで区間が細切れにならず、話者の交代では切れる長さ。
+ * - maxSpeechDuration: Haas は 30 秒前後までの発話で学習されている。長い独演は 20 秒で切り、
+ * 認識器に渡すメモリも抑える(長く渡すほどエンコーダの確保が伸びる)。
+ */
+const VAD_OPTIONS = {
+ threshold: 0.5,
+ minSilenceDuration: 0.5,
+ minSpeechDuration: 0.25,
+ maxSpeechDuration: 20
+} as const
+
+/**
+ * sherpa-onnx-node で Haas-ja-v1.0 と Silero VAD のセッションを作る。
+ *
+ * 変換版は sherpa-onnx の `nemo_transducer` として読める。特徴量は 128 次元の log-mel。
+ * 用語集(hotwords)は modified_beam_search でしか効かず、TDT での動作を確かめていないので greedy で読む。
+ */
+export class SherpaHaasSessionFactory implements HaasSessionFactory {
+ async create(config: HaasModelPaths): Promise {
+ for (const path of [
+ config.encoderPath,
+ config.decoderPath,
+ config.joinerPath,
+ config.tokensPath,
+ config.vadModelPath
+ ]) {
+ // パスが不正なままネイティブへ渡すと、原因の分からないエラーになる。
+ if (!existsSync(path)) throw new TranscriptionError({ code: 'haasModelNotConfigured' })
+ }
+
+ const sherpa = await loadSherpa(
+ (detail, cause) => new TranscriptionError({ code: 'sherpaLoadFailed', detail, forDiarization: false }, { cause })
+ )
+ const numThreads = sherpaThreads()
+ const recognizer = new sherpa.OfflineRecognizer({
+ featConfig: { sampleRate: SAMPLE_RATE, featureDim: 128 },
+ modelConfig: {
+ transducer: { encoder: config.encoderPath, decoder: config.decoderPath, joiner: config.joinerPath },
+ tokens: config.tokensPath,
+ numThreads,
+ modelType: 'nemo_transducer',
+ debug: 0
+ },
+ decodingMethod: 'greedy_search'
+ })
+
+ return {
+ sampleRate: SAMPLE_RATE,
+ resample: (samples, fromRate) => new sherpa.LinearResampler(fromRate, SAMPLE_RATE).flush(samples),
+ detectSpeech: (samples) => {
+ const vad = new sherpa.Vad(
+ {
+ sileroVad: { model: config.vadModelPath, windowSize: VAD_WINDOW, ...VAD_OPTIONS },
+ sampleRate: SAMPLE_RATE,
+ numThreads: 1,
+ debug: 0
+ },
+ // 区間を溜めるバッファ。取り出しながら流すので、最長の区間より長ければ足りる。
+ VAD_OPTIONS.maxSpeechDuration * 3
+ )
+ const spans: HaasSpeechSpan[] = []
+ const drain = (): void => {
+ while (!vad.isEmpty()) {
+ // 外部バッファは Electron の V8 が禁じていて必ず失敗する(素の Node では通る)。
+ const segment = vad.front(false)
+ vad.pop()
+ spans.push({ startSample: segment.start, samples: segment.samples })
+ }
+ }
+ for (let i = 0; i + VAD_WINDOW <= samples.length; i += VAD_WINDOW) {
+ vad.acceptWaveform(samples.subarray(i, i + VAD_WINDOW))
+ drain()
+ }
+ vad.flush()
+ drain()
+ return spans
+ },
+ recognize: (samples) => {
+ const stream = recognizer.createStream()
+ stream.acceptWaveform({ sampleRate: SAMPLE_RATE, samples })
+ recognizer.decode(stream)
+ const result = recognizer.getResult(stream)
+ return { tokens: result.tokens, timestamps: result.timestamps, logProbs: result.ys_log_probs }
+ },
+ // ネイティブ側のハンドルに解放用の API は無く、GC 時にファイナライザが片付ける。
+ // ワーカーはジョブごとに終了するので(ADR-008)、そこで確実に OS へ返る。
+ dispose: () => undefined
+ }
+ }
+}
diff --git a/src/infrastructure/transcription/SherpaHaasTranscriber.ts b/src/infrastructure/transcription/SherpaHaasTranscriber.ts
new file mode 100644
index 0000000..ab308d7
--- /dev/null
+++ b/src/infrastructure/transcription/SherpaHaasTranscriber.ts
@@ -0,0 +1,241 @@
+import type { TranscriptionPort } from '@application/ports'
+import { AppError, toMessage } from '@domain/errors'
+import type { TranscriptSegment } from '@domain/TranscriptSegment'
+import { readWav } from '@infrastructure/audio/wav'
+import { collapseRepeats, dropRepeatedSegments } from './repetition'
+import { textDropReason, type DropReason, type DroppedSegmentReporter } from './segmentFilters'
+import { TranscriptionError } from './WhisperCppTranscriber'
+
+/** Haas-ja-v1.0(sherpa-onnx 形式)のファイルと、前に掛ける VAD。 */
+export interface HaasModelPaths {
+ readonly encoderPath: string
+ readonly decoderPath: string
+ readonly joinerPath: string
+ readonly tokensPath: string
+ readonly vadModelPath: string
+}
+
+/** VAD が見つけた 1 つの発話区間。位置はモデルのサンプルレートでのサンプル番号。 */
+export interface HaasSpeechSpan {
+ readonly startSample: number
+ readonly samples: Float32Array
+}
+
+/** 1 区間の認識結果。時刻は区間の先頭からの秒。 */
+export interface HaasRecognition {
+ readonly tokens: readonly string[]
+ readonly timestamps: readonly number[]
+ readonly logProbs: readonly number[]
+}
+
+/**
+ * 1 回の文字起こしぶんのセッション。sherpa-onnx を直接触らずこの seam を挟むことで、
+ * 区切り方・時刻の換算・関門をネイティブ無しで検証できる(話者識別の DiarizationSession と同じ考え)。
+ */
+export interface HaasSession {
+ /** モデルと VAD が前提とするサンプルレート。 */
+ readonly sampleRate: number
+ resample(samples: Float32Array, fromRate: number): Float32Array
+ detectSpeech(samples: Float32Array): HaasSpeechSpan[]
+ recognize(samples: Float32Array): HaasRecognition
+ dispose(): void
+}
+
+export interface HaasSessionFactory {
+ create(config: HaasModelPaths): Promise
+}
+
+export interface SherpaHaasConfig extends HaasModelPaths {
+ /** これを下回る平均対数確率の文を落とす。既定は `HAAS_MIN_AVG_LOGPROB`。 */
+ readonly minAvgLogprob?: number
+ readonly onDropped?: DroppedSegmentReporter
+}
+
+/**
+ * 発話区間の前後に足す余白(秒)。
+ *
+ * Silero VAD は発話の始まりを少し遅れて検出する。区間だけを渡すと語頭が削れ、評価の合成音声では
+ * 「ありがとうございます」が「視聴者ございます」、「三社に」が「生産者に」になり、文頭の「はい」も消えた。
+ * VAD が区間を分ける最短の無音(0.5 秒)の半分にとどめ、隣の区間の声を取り込まない。
+ */
+const SPEECH_PAD_SEC = 0.25
+
+/** 文末の記号。Haas は句読点を付けて出すので、長い発話区間はここで分ける。 */
+const SENTENCE_END = /[。.?!?!]$/u
+
+/**
+ * 句点が無くても分ける間(秒)。VAD の区間には息継ぎ程度の間が含まれ、
+ * 相づちと次の発言が 1 行にまとまると、話者識別で区間を割り当てるときに粒度が粗くなる。
+ */
+const PAUSE_SEC = 0.6
+
+/**
+ * 文を落とす平均対数確率の下限(ADR-049)。
+ *
+ * 公開コーパスの人の声(FLEURS・Common Voice)で文ごとに測ると、普通の文はどれも -0.53 より上にあり、
+ * 下回ったのは息や雑音から出た「むぅ」「ん」のような 1〜3 字の断片だった(本物の語は「この」の -0.84 だけ)。
+ * 無音のクリップで VAD をすり抜けた区間から出た「下がり、」は -1.41。whisper と同じ -1 で、断片と作り話を落とし本物を残す。
+ */
+export const HAAS_MIN_AVG_LOGPROB = -1
+
+/**
+ * Haas が息や雑音から出す、会議の発言になりえない断片(小文字・末尾の句読点なしで書く)。
+ * 確信度の下限をすり抜けた分(-0.7 前後)の保険。「ん」「ふむ」は相づちや考え込む声として実際に言われうるので載せない。
+ */
+const HAAS_BOILERPLATE: readonly string[] = ['む', 'むぅ']
+
+/**
+ * Haas-ja-v1.0 を sherpa-onnx-node で動かす文字起こし(ADR-049)。
+ *
+ * whisper と違い、VAD で喋っている区間だけを切り出してから認識する。Haas は 30 秒前後の
+ * 発話で学習されており、録音を丸ごと渡すとメモリが伸びるうえ、無音や BGM の区間からも
+ * 文を作りうるため。区間の外は認識器に入らないので、そこからハルシネーションは生まれない。
+ */
+export class SherpaHaasTranscriber implements TranscriptionPort {
+ constructor(
+ private readonly config: SherpaHaasConfig,
+ private readonly factory: HaasSessionFactory
+ ) {}
+
+ async transcribe(params: {
+ wavPath: string
+ language: string
+ speakerId: string
+ signal?: AbortSignal
+ onProgress?: (fraction: number) => void
+ }): Promise {
+ const { encoderPath, decoderPath, joinerPath, tokensPath, vadModelPath } = this.config
+ if (!encoderPath || !decoderPath || !joinerPath || !tokensPath || !vadModelPath) {
+ throw new TranscriptionError({ code: 'haasModelNotConfigured' })
+ }
+
+ const audio = await readWav(params.wavPath)
+ if (audio.samples.length === 0) return []
+
+ const session = await this.factory.create(this.config)
+ try {
+ const pcm = toFloat(audio.samples)
+ const samples = audio.sampleRate === session.sampleRate ? pcm : session.resample(pcm, audio.sampleRate)
+ const pieces: Piece[] = []
+
+ const pad = Math.round(SPEECH_PAD_SEC * session.sampleRate)
+ for (const span of session.detectSpeech(samples)) {
+ params.signal?.throwIfAborted()
+ const spanEnd = span.startSample + span.samples.length
+ const from = Math.max(0, span.startSample - pad)
+ const to = Math.min(samples.length, spanEnd + pad)
+ const recognized = session.recognize(samples.subarray(from, to))
+ pieces.push(...splitSentences(recognized, from / session.sampleRate, spanEnd / session.sampleRate))
+ params.onProgress?.(spanEnd / samples.length)
+ }
+ params.onProgress?.(1)
+
+ return this.filter(pieces, params.speakerId)
+ } catch (error: unknown) {
+ if (error instanceof AppError) throw error
+ throw new TranscriptionError({ code: 'transcriptionFailed', detail: toMessage(error) }, { cause: error })
+ } finally {
+ // ネイティブが確保したメモリを抱えたまま次のトラックや話者識別へ進ませない。
+ session.dispose()
+ }
+ }
+
+ /** whisper と同じ順で関門に掛ける。ループを縮めてから定型句と確信度を見る。 */
+ private filter(pieces: readonly Piece[], speakerId: string): TranscriptSegment[] {
+ const { onDropped, minAvgLogprob = HAAS_MIN_AVG_LOGPROB } = this.config
+ const segments = pieces.flatMap((piece): TranscriptSegment[] => {
+ const { text, removed } = collapseRepeats(piece.text)
+ const segment = { startMs: piece.startMs, endMs: piece.endMs, speakerId, text }
+ if (removed) onDropped?.({ ...segment, text: removed, reason: 'repetition' })
+
+ const reason: DropReason | undefined =
+ textDropReason(text, HAAS_BOILERPLATE) ?? (piece.avgLogprob < minAvgLogprob ? 'low-confidence' : undefined)
+ if (reason === undefined) return [segment]
+
+ onDropped?.({ ...segment, reason, avgLogprob: piece.avgLogprob })
+ return []
+ })
+
+ const { kept, dropped } = dropRepeatedSegments(segments)
+ for (const segment of dropped) onDropped?.({ ...segment, reason: 'repetition' })
+ return kept
+ }
+}
+
+interface Piece {
+ readonly startMs: number
+ readonly endMs: number
+ readonly text: string
+ readonly avgLogprob: number
+}
+
+/**
+ * 1 区間の認識結果を文ごとに分ける。各文の終わりは次の文の最初のトークンの時刻、
+ * 最後の文は区間の終わりにする(トークンの時刻は始まりしか表さないため)。
+ */
+const splitSentences = (result: HaasRecognition, startSec: number, endSec: number): Piece[] => {
+ const groups: number[][] = []
+ let current: number[] = []
+ result.tokens.forEach((token, index) => {
+ const previous = current[current.length - 1]
+ if (previous !== undefined && at(result, index) - at(result, previous) >= PAUSE_SEC) {
+ groups.push(current)
+ current = []
+ }
+ current.push(index)
+ if (SENTENCE_END.test(token)) {
+ groups.push(current)
+ current = []
+ }
+ })
+ if (current.length > 0) groups.push(current)
+
+ return groups.flatMap((group, index): Piece[] => {
+ const first = group[0]
+ if (first === undefined) return []
+ const text = joinTokens(group.map((i) => result.tokens[i] ?? ''))
+ if (text.length === 0) return []
+
+ const next = groups[index + 1]?.[0]
+ const probs = group.map((i) => result.logProbs[i] ?? 0)
+ return [
+ {
+ startMs: Math.round((startSec + at(result, first)) * 1000),
+ endMs: Math.round((next === undefined ? endSec : startSec + at(result, next)) * 1000),
+ text,
+ avgLogprob: probs.reduce((sum, p) => sum + p, 0) / probs.length
+ }
+ ]
+ })
+}
+
+const at = (result: HaasRecognition, index: number): number => result.timestamps[index] ?? 0
+
+/**
+ * トークンをつなぐ。SentencePiece の語頭の印は空白として届くので、日本語の文字に接する空白は落とし、
+ * 英単語どうしの間(「Google Meet」など)だけ残す。
+ */
+export const joinTokens = (tokens: readonly string[]): string =>
+ decodeByteTokens(tokens.join(''))
+ .replace(/\s+/gu, ' ')
+ .replace(/ (?=\P{ASCII})|(?<=\P{ASCII}) /gu, '')
+ .trim()
+
+/**
+ * 語彙(3,072 語)に無い字は、SentencePiece の byte fallback で UTF-8 の 1 バイトずつ `<0xE6>` の形で届く。
+ * sherpa-onnx は全体の text では戻すが、トークンの列はそのままなので、文に分けて組み立てる側で戻す。
+ * 連なりの途中で切れて UTF-8 として不完全なら、置換文字(U+FFFD)になる。
+ */
+const BYTE_TOKENS = /(?:<0x[0-9A-Fa-f]{2}>)+/gu
+
+const decodeByteTokens = (text: string): string =>
+ text.replace(BYTE_TOKENS, (run) =>
+ new TextDecoder().decode(Uint8Array.from(run.match(/[0-9A-Fa-f]{2}(?=>)/gu) ?? [], (hex) => parseInt(hex, 16)))
+ )
+
+/** sherpa-onnx は [-1, 1] の Float32 を受け取る。 */
+const toFloat = (samples: Int16Array): Float32Array => {
+ const float = new Float32Array(samples.length)
+ for (let i = 0; i < samples.length; i += 1) float[i] = (samples[i] ?? 0) / 32_768
+ return float
+}
diff --git a/src/infrastructure/transcription/WhisperCppTranscriber.ts b/src/infrastructure/transcription/WhisperCppTranscriber.ts
index b44a5e8..6b0cd6a 100644
--- a/src/infrastructure/transcription/WhisperCppTranscriber.ts
+++ b/src/infrastructure/transcription/WhisperCppTranscriber.ts
@@ -5,6 +5,7 @@ import { AppError, toMessage, type ErrorReason } from '@domain/errors'
import { glossaryPrompt } from '@domain/Glossary'
import type { TranscriptSegment } from '@domain/TranscriptSegment'
import { wavDurationMs } from '@infrastructure/audio/wav'
+import { textDropReason, type DropReason, type DroppedSegment, type DroppedSegmentReporter } from './segmentFilters'
import { collapseRepeats, dropRepeatedSegments } from './repetition'
export class TranscriptionError extends AppError {}
@@ -94,27 +95,8 @@ export const averageLogprob = (tokens: readonly { text?: string; p?: number }[]
return probs.reduce((sum, p) => sum + Math.log(p), 0) / probs.length
}
-/** セグメントを落とした関門。閾値を見直すには、どこで落ちたかが要る。 */
-export type DropReason = 'non-speech' | 'boilerplate' | 'low-confidence' | 'repetition'
-
-/** 落としたセグメントの記録。計測モードでのみ作られる。 */
-export interface DroppedSegment {
- readonly speakerId: string
- readonly startMs: number
- readonly endMs: number
- readonly text: string
- readonly reason: DropReason
- /** 確率を持つトークンがあったときだけ入る。 */
- readonly avgLogprob?: number
-}
-
-/**
- * 落としたセグメントの通知先。
- *
- * 出力先をここで決めないのは、`console` を持たない呼び出し元(テスト、将来の
- * ファイル出力)からも同じ経路で受け取れるようにするため。
- */
-export type DroppedSegmentReporter = (dropped: DroppedSegment) => void
+// 落とした記録の型はエンジンに依らないので共有モジュールに置き、既存の import のために出し直す。
+export type { DropReason, DroppedSegment, DroppedSegmentReporter } from './segmentFilters'
/** `1:02:03.450` 形式。会議は 1 時間を超えるので時まで出す。 */
const formatTimestamp = (ms: number): string => {
@@ -391,54 +373,12 @@ const splitAtVadGaps = (piece: SegmentPiece, spans: readonly VadSpan[]): Segment
/** セグメントを落とす理由。落とさないなら undefined。 */
const dropReason = (text: string, logprob: number | undefined): DropReason | undefined => {
- if (NON_SPEECH.test(text)) return 'non-speech'
- if (isHallucination(text)) return 'boilerplate'
+ const byText = textDropReason(text)
+ if (byText !== undefined) return byText
if (logprob !== undefined && logprob < MIN_AVG_LOGPROB) return 'low-confidence'
return undefined
}
-/** whisper が挿入する非発話マーカー。 */
-const NON_SPEECH = /^(\[[^\]]*\]|\([^)]*\)|♪+|*+)$/
-
-/**
- * 無音区間で whisper が生みやすい定型句。VAD をすり抜けた分の保険。
- *
- * whisper の学習データには字幕が大量に含まれるため、音声が無いと動画の
- * 締めの決まり文句を出力する。セグメント全体がこれらと一致したときだけ
- * 落とす(部分一致で消すと「資料の共有ありがとうございました」のような
- * 本物の発言まで失われる)。
- *
- * 載せるのは動画の文脈でしか出てこない固有性の高い言い回しに限る。
- * 「終わり」のような短く汎用的な語は、会議の締めで実際に発せられたものと
- * 区別がつかず、黙って消すほうが害が大きい。
- */
-const HALLUCINATIONS: readonly string[] = [
- 'ご視聴ありがとうございました',
- 'ご視聴ありがとうございます',
- 'ご清聴ありがとうございました',
- 'ご清聴ありがとうございます',
- '最後までご視聴いただきありがとうございました',
- 'チャンネル登録よろしくお願いします',
- 'チャンネル登録高評価よろしくお願いします',
- 'この動画が良かったと思ったらチャンネル登録よろしくお願いします',
- '次回の動画でお会いしましょう',
- // 英語の会議でも無音から同じ種類の定型句が生まれる(ADR-043)。比較は小文字で行う。
- 'thank you for watching',
- 'thanks for watching',
- 'thank you so much for watching',
- 'thanks for watching and see you next time',
- 'please subscribe to my channel',
- 'please like and subscribe',
- 'see you in the next video'
-]
-
-/** 末尾の句読点や感嘆符は揺れるだけで意味を持たないため、比較前に落とす。 */
-const stripTrailingPunctuation = (text: string): string => text.replace(/[。..、,,!!??〜~…\s]+$/u, '')
-
-/** 英語は文頭の大文字が揺れる。日本語には影響しない。 */
-const isHallucination = (text: string): boolean =>
- HALLUCINATIONS.includes(stripTrailingPunctuation(text).trim().toLowerCase())
-
/**
* サンプルを 1 つも持たない WAV かどうか。
*
diff --git a/src/infrastructure/transcription/segmentFilters.ts b/src/infrastructure/transcription/segmentFilters.ts
new file mode 100644
index 0000000..30c883c
--- /dev/null
+++ b/src/infrastructure/transcription/segmentFilters.ts
@@ -0,0 +1,81 @@
+/**
+ * テキストだけで判断できる関門。エンジンに依らないので、whisper と Haas で共用する(ADR-049)。
+ * 確信度やタイムスタンプで判断する関門は、エンジンごとの出力の形に依るので各実装が持つ。
+ */
+
+/** セグメントを落とした関門。閾値を見直すには、どこで落ちたかが要る。 */
+export type DropReason = 'non-speech' | 'boilerplate' | 'low-confidence' | 'repetition'
+
+/** 落としたセグメントの記録。計測モードでのみ作られる。 */
+export interface DroppedSegment {
+ readonly speakerId: string
+ readonly startMs: number
+ readonly endMs: number
+ readonly text: string
+ readonly reason: DropReason
+ /** 確率を持つトークンがあったときだけ入る。 */
+ readonly avgLogprob?: number
+}
+
+/**
+ * 落としたセグメントの通知先。
+ *
+ * 出力先をここで決めないのは、`console` を持たない呼び出し元(テスト、将来の
+ * ファイル出力)からも同じ経路で受け取れるようにするため。
+ */
+export type DroppedSegmentReporter = (dropped: DroppedSegment) => void
+
+/** whisper が挿入する非発話マーカー。Haas は出さないが、出ても発言ではないので共用する。 */
+const NON_SPEECH = /^(\[[^\]]*\]|\([^)]*\)|♪+|*+)$/
+
+/**
+ * 無音区間で whisper が生みやすい定型句。VAD をすり抜けた分の保険。
+ *
+ * whisper の学習データには字幕が大量に含まれるため、音声が無いと動画の
+ * 締めの決まり文句を出力する。セグメント全体がこれらと一致したときだけ
+ * 落とす(部分一致で消すと「資料の共有ありがとうございました」のような
+ * 本物の発言まで失われる)。
+ *
+ * 載せるのは動画の文脈でしか出てこない固有性の高い言い回しに限る。
+ * 「終わり」のような短く汎用的な語は、会議の締めで実際に発せられたものと
+ * 区別がつかず、黙って消すほうが害が大きい。
+ */
+const HALLUCINATIONS: readonly string[] = [
+ 'ご視聴ありがとうございました',
+ 'ご視聴ありがとうございます',
+ 'ご清聴ありがとうございました',
+ 'ご清聴ありがとうございます',
+ '最後までご視聴いただきありがとうございました',
+ 'チャンネル登録よろしくお願いします',
+ 'チャンネル登録高評価よろしくお願いします',
+ 'この動画が良かったと思ったらチャンネル登録よろしくお願いします',
+ '次回の動画でお会いしましょう',
+ // 英語の会議でも無音から同じ種類の定型句が生まれる(ADR-043)。比較は小文字で行う。
+ 'thank you for watching',
+ 'thanks for watching',
+ 'thank you so much for watching',
+ 'thanks for watching and see you next time',
+ 'please subscribe to my channel',
+ 'please like and subscribe',
+ 'see you in the next video'
+]
+
+/** 末尾の句読点や感嘆符は揺れるだけで意味を持たないため、比較前に落とす。 */
+const stripTrailingPunctuation = (text: string): string => text.replace(/[。..、,,!!??〜~…\s]+$/u, '')
+
+/** 英語は文頭の大文字が揺れる。日本語には影響しない。 */
+const matches = (list: readonly string[], text: string): boolean =>
+ list.includes(stripTrailingPunctuation(text).trim().toLowerCase())
+
+/**
+ * セグメントをテキストだけで落とす理由。落とさないなら undefined。
+ * `extraBoilerplate` はエンジン固有の定型句(小文字・末尾の句読点なしで書く)。
+ */
+export const textDropReason = (
+ text: string,
+ extraBoilerplate: readonly string[] = []
+): 'non-speech' | 'boilerplate' | undefined => {
+ if (NON_SPEECH.test(text)) return 'non-speech'
+ if (matches(HALLUCINATIONS, text) || matches(extraBoilerplate, text)) return 'boilerplate'
+ return undefined
+}
diff --git a/src/main/worker/pipeline-container.ts b/src/main/worker/pipeline-container.ts
index 3cf1a54..4f09869 100644
--- a/src/main/worker/pipeline-container.ts
+++ b/src/main/worker/pipeline-container.ts
@@ -1,6 +1,6 @@
import { existsSync } from 'node:fs'
import { join } from 'node:path'
-import type { DiarizationPort, ProgressReporterPort, SpeakerEmbeddingPort } from '@application/ports'
+import type { DiarizationPort, ProgressReporterPort, SpeakerEmbeddingPort, TranscriptionPort } from '@application/ports'
import { ExtractVoices } from '@application/usecases/ExtractVoices'
import { ProcessRecording } from '@application/usecases/ProcessRecording'
import { resolveAudioConvBinary } from '@infrastructure/audio/resolveAudioConvBinary'
@@ -19,10 +19,17 @@ import { NodeLlamaSessionFactory } from '@infrastructure/summarization/NodeLlama
import { resolveAppleLmBinary } from '@infrastructure/summarization/resolveAppleLmBinary'
import { NodeSystemResourceProbe } from '@infrastructure/system/NodeSystemResourceProbe'
import { resolveBundledBinary } from '@infrastructure/system/resolveBundledBinary'
-import { WhisperCppTranscriber, droppedSegmentLogger } from '@infrastructure/transcription/WhisperCppTranscriber'
+import { SherpaHaasSessionFactory } from '@infrastructure/transcription/SherpaHaasSessionFactory'
+import { SherpaHaasTranscriber } from '@infrastructure/transcription/SherpaHaasTranscriber'
+import {
+ WhisperCppTranscriber,
+ droppedSegmentLogger,
+ type DroppedSegmentReporter
+} from '@infrastructure/transcription/WhisperCppTranscriber'
import { resolveWhisperBinary } from '@infrastructure/transcription/resolveWhisperBinary'
import {
summarizationProviderOf,
+ transcriptionEngineOf,
type DiarizationSettings,
type Settings,
type TranscriptionSettings
@@ -56,17 +63,7 @@ export const createPipeline = async (
artifacts: new FileRecordingArtifactStore(locator, join(userDataPath, 'work')),
mixer: new TrackMixer(),
encoder: audioConverters().encoder,
- transcriber: new WhisperCppTranscriber({
- binaryPath: resolveWhisperBinary({
- configured: current.transcription.binaryPath,
- ...(bundled === undefined ? {} : { bundled })
- }),
- modelPath: current.transcription.modelPath,
- vadModelPath: resolveVadModel(current.transcription),
- glossary: current.transcription.glossary,
- // 閾値を見直すための計測モード。既定では undefined が入り、何も記録しない。
- ...(dropped === undefined ? {} : { onDropped: dropped })
- }),
+ transcriber: createTranscriber(current, bundled, dropped),
diarizer: createDiarizer(current.diarization),
embedder: createEmbedder(current.diarization),
voiceprints: new FileVoiceprintRepository(locator),
@@ -74,6 +71,43 @@ export const createPipeline = async (
})
}
+/**
+ * 設定で選んだエンジンで文字起こしする(ADR-049)。Haas は会議の言語が日本語のときだけ使い、
+ * それ以外は whisper に任せる(判断は `transcriptionEngineOf`)。
+ */
+const createTranscriber = (
+ current: Settings,
+ bundled: string | undefined,
+ // 閾値を見直すための計測モード。既定では undefined が入り、何も記録しない。
+ dropped: DroppedSegmentReporter | undefined
+): TranscriptionPort => {
+ const config = current.transcription
+ if (transcriptionEngineOf(current) === 'haas-ja') {
+ return new SherpaHaasTranscriber(
+ {
+ encoderPath: config.haasEncoderPath,
+ decoderPath: config.haasDecoderPath,
+ joinerPath: config.haasJoinerPath,
+ tokensPath: config.haasTokensPath,
+ vadModelPath: config.haasVadModelPath,
+ ...(dropped === undefined ? {} : { onDropped: dropped })
+ },
+ new SherpaHaasSessionFactory()
+ )
+ }
+
+ return new WhisperCppTranscriber({
+ binaryPath: resolveWhisperBinary({
+ configured: config.binaryPath,
+ ...(bundled === undefined ? {} : { bundled })
+ }),
+ modelPath: config.modelPath,
+ vadModelPath: resolveVadModel(config),
+ glossary: config.glossary,
+ ...(dropped === undefined ? {} : { onDropped: dropped })
+ })
+}
+
/**
* 声紋の取り直し用の依存を組み立てる。
*
diff --git a/src/renderer/i18n/licenses.ts b/src/renderer/i18n/licenses.ts
index 5a76071..27620d8 100644
--- a/src/renderer/i18n/licenses.ts
+++ b/src/renderer/i18n/licenses.ts
@@ -33,6 +33,7 @@ const ja: {
'システム音声の取り込みに使っています。配布元が著作権表示を掲げていないため、ライセンスの種別だけを示します。',
ggmlConversionByWhisperCpp: 'ggml 形式への変換は whisper.cpp の配布物を使っています。',
onnxConversionBySherpa: 'sherpa-onnx が配布する ONNX 変換版を使っています。',
+ onnxConversionByOboroge0: 'oboroge0 による ONNX 変換・量子化版(Haas-ja-v1.0-onnx-quantized)を使っています。',
ggufConversionByGgmlOrg: 'GGUF 形式への変換は ggml-org の配布物を使っています。'
}
}
@@ -63,6 +64,7 @@ const en: typeof ja = {
'Used to capture system audio. The distributor does not publish a copyright notice, so only the license type is shown.',
ggmlConversionByWhisperCpp: 'The ggml conversion distributed by whisper.cpp is used.',
onnxConversionBySherpa: 'The ONNX conversion distributed by sherpa-onnx is used.',
+ onnxConversionByOboroge0: 'The quantized ONNX conversion by oboroge0 (Haas-ja-v1.0-onnx-quantized) is used.',
ggufConversionByGgmlOrg: 'The GGUF conversion distributed by ggml-org is used.'
}
}
diff --git a/src/renderer/i18n/settings.ts b/src/renderer/i18n/settings.ts
index 44aa3f0..271f025 100644
--- a/src/renderer/i18n/settings.ts
+++ b/src/renderer/i18n/settings.ts
@@ -28,6 +28,15 @@ const ja = {
},
transcription: {
methodCardTitle: '文字起こしの方法',
+ engineLabel: 'エンジン',
+ engineHint: 'Haas は日本語専用で、日本語の認識の誤りが Whisper より少ないモデルです。',
+ engineWhisper: 'Whisper(large-v3-turbo)',
+ engineHaas: 'Haas(Haas-ja-v1.0)',
+ haasCaution:
+ 'Haas では用語集が効かず、無音区間は設定に関わらず常に除きます(無音や BGM から文が生まれるのを防ぐため)。',
+ haasLanguageCaution:
+ '言語が「日本語」以外なので、録音は Whisper で文字起こしします。Haas を使うには言語を「日本語」にしてください。',
+ haasModelMissing: 'Haas のモデルがまだ取得されていません。「モデル」で取得してください。',
languageLabel: '言語',
languageOptionJa: '日本語',
languageOptionEn: '英語',
@@ -161,6 +170,15 @@ const en: typeof ja = {
},
transcription: {
methodCardTitle: 'Transcription method',
+ engineLabel: 'Engine',
+ engineHint: 'Haas is a Japanese-only model that makes fewer recognition errors in Japanese than Whisper.',
+ engineWhisper: 'Whisper (large-v3-turbo)',
+ engineHaas: 'Haas (Haas-ja-v1.0)',
+ haasCaution:
+ 'With Haas, the glossary has no effect, and silent stretches are always skipped regardless of the setting (so silence and background music do not turn into sentences).',
+ haasLanguageCaution:
+ 'The language is not set to Japanese, so recordings are transcribed with Whisper. Set the language to Japanese to use Haas.',
+ haasModelMissing: 'The Haas model has not been downloaded yet. Download it under Models.',
languageLabel: 'Language',
languageOptionJa: 'Japanese',
languageOptionEn: 'English',
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index d3f30ad..e624a8c 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -926,6 +926,18 @@ code {
color: color-mix(in srgb, var(--warning) 55%, var(--text));
}
+/* 注意が複数あるとき(Haas の言語・未取得など)は段落に分ける。 */
+.settings__caution p {
+ margin: 0;
+}
+/* 欄の間に置いたときは、次の欄と詰まらないようにする。 */
+div.settings__caution {
+ margin-bottom: 16px;
+}
+.settings__caution p + p {
+ margin-top: 6px;
+}
+
/* 失敗ではないが伝えておきたいこと(声紋を覚えられなかった等)。 */
.detail__notice {
margin: 0;
diff --git a/src/renderer/views/SettingsView.tsx b/src/renderer/views/SettingsView.tsx
index 3b442e0..0c6b412 100644
--- a/src/renderer/views/SettingsView.tsx
+++ b/src/renderer/views/SettingsView.tsx
@@ -8,6 +8,8 @@ import {
customSummaryPromptSeed,
settingsSummaryPrompt,
summarizationProviderOf,
+ TRANSCRIPTION_PROVIDERS,
+ transcriptionProviderOf,
updateCheckIntervalOf,
type Settings,
type SettingsPatch
@@ -60,6 +62,7 @@ export const SettingsView = ({
const settings = setup.settings
const t = settingsText()
const usesGemma = summarizationProviderOf(settings) === 'llama-cpp'
+ const usesHaas = transcriptionProviderOf(settings) === 'haas-ja'
const customPrompt = settings.summarization.promptMode === 'custom'
// OS に無い機能の設定は出さない(ADR-048)。
const features = platformFeatures(platform())
@@ -159,6 +162,27 @@ export const SettingsView = ({
transcription: (
<>
+
+
+
+ {/* 選んでいる間はずっと見せる。日本語以外の録音が黙って whisper で起こされると、選んだ意味を疑わせる。 */}
+ {usesHaas && (
+
+
{t.transcription.haasCaution}
+ {settings.transcription.language !== 'ja' &&
{t.transcription.haasLanguageCaution}
}
+ {!settings.transcription.haasEncoderPath &&
{t.transcription.haasModelMissing}
}
+
+ )}
+