From 84030118357717f80363d005dfcf8263d8a6af07 Mon Sep 17 00:00:00 2001 From: eddybean <38001995+eddybean@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:22:50 +0900 Subject: [PATCH 1/3] =?UTF-8?q?=E6=96=87=E5=AD=97=E8=B5=B7=E3=81=93?= =?UTF-8?q?=E3=81=97=E3=81=AE=E3=82=A8=E3=83=B3=E3=82=B8=E3=83=B3=E3=81=AB?= =?UTF-8?q?=20Haas-ja-v1.0=20=E3=82=92=E9=81=B8=E3=81=B9=E3=82=8B=E3=82=88?= =?UTF-8?q?=E3=81=86=E3=81=AB=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit sherpa-onnx-node の OfflineRecognizer(nemo_transducer)と Silero VAD で、 有志の量子化版(oboroge0/Haas-ja-v1.0-onnx-quantized)を動かす。 VAD で切り出した発話区間だけを認識し、文末と間で分けて録音の時刻に戻す。 テキストで判断する関門は whisper と共用にし、日本語以外の録音は whisper に任せる。 Co-Authored-By: Claude Opus 5.5 --- src/application/usecases/ProcessRecording.ts | 17 +- src/application/usecases/models.ts | 13 + src/domain/ModelCatalog.ts | 105 ++++++- src/domain/Settings.ts | 52 +++- src/domain/ThirdPartyNotices.ts | 10 +- src/domain/errors.ts | 2 + .../diarization/sherpaModule.ts | 10 +- .../transcription/SherpaHaasSessionFactory.ts | 104 +++++++ .../transcription/SherpaHaasTranscriber.ts | 213 ++++++++++++++ .../transcription/WhisperCppTranscriber.ts | 70 +---- .../transcription/segmentFilters.ts | 81 ++++++ src/main/worker/pipeline-container.ts | 60 +++- src/renderer/i18n/licenses.ts | 2 + src/renderer/i18n/settings.ts | 18 ++ src/renderer/styles.css | 8 + src/renderer/views/SettingsView.tsx | 24 ++ src/shared/i18n/errors.ts | 6 + src/shared/i18n/models.ts | 30 +- src/types/sherpa-onnx-node.d.ts | 71 +++++ tests/application/models.test.ts | 9 +- tests/application/process-recording.test.ts | 28 ++ tests/domain/model-catalog.test.ts | 44 ++- tests/domain/settings.test.ts | 42 +++ tests/infrastructure/haas-session.test.ts | 77 +++++ tests/infrastructure/haas-transcriber.test.ts | 274 ++++++++++++++++++ tests/infrastructure/segment-filters.test.ts | 23 ++ tests/infrastructure/sherpa-interop.test.ts | 20 ++ 27 files changed, 1313 insertions(+), 100 deletions(-) create mode 100644 src/infrastructure/transcription/SherpaHaasSessionFactory.ts create mode 100644 src/infrastructure/transcription/SherpaHaasTranscriber.ts create mode 100644 src/infrastructure/transcription/segmentFilters.ts create mode 100644 tests/infrastructure/haas-session.test.ts create mode 100644 tests/infrastructure/haas-transcriber.test.ts create mode 100644 tests/infrastructure/segment-filters.test.ts 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..5f42489 --- /dev/null +++ b/src/infrastructure/transcription/SherpaHaasTranscriber.ts @@ -0,0 +1,213 @@ +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 { + /** + * これを下回る平均対数確率のセグメントを落とす。未指定なら確信度では落とさない。 + * whisper の -1 は whisper の確率の分布で決めた値で、Haas にそのまま当てはまる根拠が無い。 + */ + readonly minAvgLogprob?: number + readonly onDropped?: DroppedSegmentReporter +} + +/** 文末の記号。Haas は句読点を付けて出すので、長い発話区間はここで分ける。 */ +const SENTENCE_END = /[。.?!?!]$/u + +/** + * 句点が無くても分ける間(秒)。VAD の区間には息継ぎ程度の間が含まれ、 + * 相づちと次の発言が 1 行にまとまると、話者識別で区間を割り当てるときに粒度が粗くなる。 + */ +const PAUSE_SEC = 0.6 + +/** + * Haas で頻出する定型句(小文字・末尾の句読点なしで書く)。whisper の一覧と同じく、 + * 会議では言われない、固有性の高い言い回しだけを載せる(ADR-049)。 + */ +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[] = [] + + for (const span of session.detectSpeech(samples)) { + params.signal?.throwIfAborted() + const startSec = span.startSample / session.sampleRate + const endSec = startSec + span.samples.length / session.sampleRate + pieces.push(...splitSentences(session.recognize(span.samples), startSec, endSec)) + params.onProgress?.((span.startSample + span.samples.length) / 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 } = 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) ?? + (minAvgLogprob !== undefined && 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 => + tokens + .join('') + .replace(/\s+/gu, ' ') + .replace(/ (?=[^\x00-\x7F])|(?<=[^\x00-\x7F]) /gu, '') + .trim() + +/** 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..566b3c0 100644 --- a/src/renderer/styles.css +++ b/src/renderer/styles.css @@ -926,6 +926,14 @@ code { color: color-mix(in srgb, var(--warning) 55%, var(--text)); } +/* 注意が複数あるとき(Haas の言語・未取得など)は段落に分ける。 */ +.settings__caution p { + margin: 0; +} +.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}

} +
+ )} +