using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Speech.Recognition; using ChaoXingAutoClass.Core; using NAudio.Wave; using Whisper.net; namespace ChaoXingAutoClass.Speech; public sealed class WhisperTranscriber(IMediaDownloader media, AppSettings settings, string modelDirectory, Action? progress = null) : ILessonTranscriber, IDisposable { private readonly SemaphoreSlim _gate = new(1, 1); private WhisperFactory? _factory; public async Task TranscribeAsync(VideoState video, string directory, CancellationToken cancellationToken) { await _gate.WaitAsync(cancellationToken); try { Directory.CreateDirectory(directory); progress?.Invoke("正在取得当前视频的真实音轨…"); var input = await media.DownloadMediaAsync(video, directory, cancellationToken); var wave = Path.ChangeExtension(input, ".wav"); await Task.Run(() => ExtractAudio(input, wave, cancellationToken), cancellationToken); return await TranscribeWaveAsync(wave, directory, cancellationToken); } finally { _gate.Release(); } } public async Task TranscribeWaveAsync(string wave, string directory, CancellationToken cancellationToken) { if (new FileInfo(wave).Length <= 44) throw new InvalidOperationException("音轨为空,无法转写。"); var cachedWhisper = !string.IsNullOrWhiteSpace(settings.WhisperModelPath) || File.Exists(Path.Combine(modelDirectory, $"ggml-{settings.WhisperModel}.bin")); var useWindows = settings.TranscriptionEngine == "windows" || (settings.TranscriptionEngine == "auto" && !cachedWhisper); var recognizer = useWindows ? SpeechRecognitionEngine.InstalledRecognizers() .FirstOrDefault(info => settings.WhisperLanguage == "auto" || info.Culture.TwoLetterISOLanguageName == settings.WhisperLanguage) : null; List segments; if (recognizer is not null) segments = await TranscribeWithWindowsAsync(wave, recognizer, cancellationToken); else { if (settings.TranscriptionEngine == "windows") throw new InvalidOperationException("Windows 没有安装所选语言的语音识别引擎,请切换到 Whisper 或安装对应语言包。"); var model = await EnsureModelAsync(cancellationToken); cancellationToken.ThrowIfCancellationRequested(); _factory ??= WhisperFactory.FromPath(model); using var processor = _factory.CreateBuilder().WithLanguage(settings.WhisperLanguage) .WithThreads(Math.Clamp(Environment.ProcessorCount / 2, 1, 8)).Build(); await using var stream = File.OpenRead(wave); progress?.Invoke($"本地 Whisper({settings.WhisperModel} / {settings.WhisperLanguage})正在转写音轨…"); segments = []; await foreach (var segment in processor.ProcessAsync(stream, cancellationToken)) { if (!string.IsNullOrWhiteSpace(segment.Text)) { segments.Add(new(segment.Start.TotalSeconds, segment.End.TotalSeconds, segment.Text.Trim())); if (segments.Count % 10 == 0) progress?.Invoke($"音轨已转写至 {segment.End:hh\\:mm\\:ss}({segments.Count} 段)"); } } } if (segments.Count == 0) throw new InvalidOperationException("没有识别到可用语音,请检查音轨或转写语言。"); var text = string.Join('\n', segments.Select(segment => $"[{TimeSpan.FromSeconds(segment.Start):hh\\:mm\\:ss}–{TimeSpan.FromSeconds(segment.End):hh\\:mm\\:ss}] {segment.Text}")); Directory.CreateDirectory(directory); var stem = Path.GetFileNameWithoutExtension(wave); var textFile = Path.Combine(directory, stem + ".transcript.txt"); await File.WriteAllTextAsync(textFile, text, cancellationToken); await File.WriteAllTextAsync(Path.Combine(directory, stem + ".transcript.srt"), ToSrt(segments), cancellationToken); await File.WriteAllTextAsync(Path.Combine(directory, stem + ".transcript.json"), JsonSerializer.Serialize(segments, new JsonSerializerOptions { WriteIndented = true }), cancellationToken); progress?.Invoke($"音轨转写完成,{segments.Count} 段;已保存 TXT / SRT / JSON。"); return new(segments.ToArray(), text, textFile); } private async Task> TranscribeWithWindowsAsync(string wave, RecognizerInfo info, CancellationToken token) { progress?.Invoke($"本地 Windows 语音识别({info.Culture.Name}),无需下载模型…"); using var engine = new SpeechRecognitionEngine(info); engine.LoadGrammar(new DictationGrammar()); engine.InitialSilenceTimeout = TimeSpan.FromSeconds(30); engine.SetInputToWaveFile(wave); var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var segments = new List(); engine.SpeechRecognized += (_, e) => { if (!string.IsNullOrWhiteSpace(e.Result.Text)) { var audio = e.Result.Audio; segments.Add(new(audio.AudioPosition.TotalSeconds, (audio.AudioPosition + audio.Duration).TotalSeconds, e.Result.Text)); if (segments.Count % 10 == 0) progress?.Invoke($"Windows 音轨已识别至 {audio.AudioPosition:hh\\:mm\\:ss}({segments.Count} 段)"); } }; engine.RecognizeCompleted += (_, e) => { if (e.Error is not null) completion.TrySetException(e.Error); else if (e.Cancelled || token.IsCancellationRequested) completion.TrySetCanceled(token); else completion.TrySetResult(); }; token.ThrowIfCancellationRequested(); engine.RecognizeAsync(RecognizeMode.Multiple); using var registration = token.Register(() => engine.RecognizeAsyncCancel()); await completion.Task; return segments; } public static void ExtractAudio(string input, string output, CancellationToken cancellationToken) { // Windows Media Foundation decodes the MP4/AAC; no microphone or system // audio recording, so muting the player does not remove the audio track. using var reader = new MediaFoundationReader(input); using var resampler = new MediaFoundationResampler(reader, new WaveFormat(16000, 16, 1)); using var writer = new WaveFileWriter(output, resampler.WaveFormat); var buffer = new byte[32000]; int count; while ((count = resampler.Read(buffer)) > 0) { cancellationToken.ThrowIfCancellationRequested(); writer.Write(buffer, 0, count); } if (writer.Length == 0) throw new InvalidOperationException("媒体没有可解码音轨。"); } public async Task EnsureModelAsync(CancellationToken cancellationToken) { if (!string.IsNullOrWhiteSpace(settings.WhisperModelPath)) { if (!File.Exists(settings.WhisperModelPath)) throw new InvalidOperationException("指定的 Whisper 模型文件不存在。"); return settings.WhisperModelPath; } Directory.CreateDirectory(modelDirectory); var fileName = $"ggml-{settings.WhisperModel}.bin"; var target = Path.Combine(modelDirectory, fileName); var expected = settings.WhisperModel == "base" ? "60ed5bc3dd14eea856493d334349b405782ddcaf0028d4b5df4088345fba2efe" : "1be3a9b2063867b937e64e2ec7483364a79917e157fa98c5d94b5c1fffea987b"; async Task VerifiedAsync(string file) { if (!File.Exists(file)) return false; await using var stream = File.OpenRead(file); return Convert.ToHexString(await SHA256.HashDataAsync(stream, cancellationToken)).Equals(expected, StringComparison.OrdinalIgnoreCase); } if (await VerifiedAsync(target)) return target; var temporary = target + $".{Guid.NewGuid():N}.download"; using var client = new HttpClient { Timeout = TimeSpan.FromMinutes(30) }; progress?.Invoke($"首次使用,正在下载 Whisper {settings.WhisperModel} 模型…"); foreach (var host in new[] { "huggingface.co", "hf-mirror.com" }) { try { using var headersTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); headersTimeout.CancelAfter(TimeSpan.FromSeconds(20)); using var response = await client.GetAsync($"https://{host}/ggerganov/whisper.cpp/resolve/main/{fileName}", HttpCompletionOption.ResponseHeadersRead, headersTimeout.Token); response.EnsureSuccessStatusCode(); headersTimeout.CancelAfter(Timeout.InfiniteTimeSpan); await using (var input = await response.Content.ReadAsStreamAsync(cancellationToken)) await using (var output = new FileStream(temporary, FileMode.Create, FileAccess.Write, FileShare.None, 65536, true)) await input.CopyToAsync(output, cancellationToken); if (!await VerifiedAsync(temporary)) throw new InvalidOperationException("Whisper 模型 SHA-256 不匹配。"); File.Move(temporary, target, true); return target; } catch (Exception error) when (!cancellationToken.IsCancellationRequested && error is HttpRequestException or TaskCanceledException) { progress?.Invoke($"模型源 {host} 暂不可用,尝试下一个来源;下载后将核对官方 SHA-256。"); } } throw new InvalidOperationException("模型下载失败,可在设置中指定本地 ggml 模型文件。"); } public static string ToSrt(IReadOnlyList segments) { static string Stamp(double seconds) => TimeSpan.FromSeconds(seconds).ToString(@"hh\:mm\:ss\,fff"); var text = new StringBuilder(); for (var index = 0; index < segments.Count; index++) text.AppendLine((index + 1).ToString()).AppendLine($"{Stamp(segments[index].Start)} --> {Stamp(segments[index].End)}") .AppendLine(segments[index].Text).AppendLine(); return text.ToString(); } public void Dispose() { _factory?.Dispose(); _gate.Dispose(); } }