BotSharp/src/Plugins/BotSharp.Plugin.AudioHandler/Provider/NativeWhisperProvider.cs

130 lines
4.1 KiB
C#
Raw Normal View History

2024-07-30 18:57:32 +00:00
using Whisper.net;
using Whisper.net.Ggml;
namespace BotSharp.Plugin.AudioHandler.Provider;
/// <summary>
/// Native Whisper provider for speech to text conversion
/// </summary>
public class NativeWhisperProvider : ISpeechToText
{
2024-08-26 22:24:07 +00:00
private readonly IAudioHelper _audioProcessor;
private static WhisperProcessor _whisperProcessor;
private readonly ILogger<NativeWhisperProvider> _logger;
public string Provider => "native";
2024-07-30 18:57:32 +00:00
2024-08-17 23:34:31 +00:00
private string MODEL_DIR = "model";
private string? _currentModelPath;
2024-08-26 22:24:07 +00:00
2024-08-17 23:34:31 +00:00
private Dictionary<GgmlType, string> _modelPathDict = new Dictionary<GgmlType, string>();
private GgmlType? _modelType;
2024-07-30 18:57:32 +00:00
2024-08-11 16:26:57 +00:00
public NativeWhisperProvider(
2024-08-26 22:24:07 +00:00
IAudioHelper audioProcessor,
2024-08-11 16:26:57 +00:00
ILogger<NativeWhisperProvider> logger)
2024-07-30 18:57:32 +00:00
{
2024-08-26 22:24:07 +00:00
_audioProcessor = audioProcessor;
2024-08-11 16:26:57 +00:00
_logger = logger;
2024-07-30 18:57:32 +00:00
}
2024-08-17 03:39:32 +00:00
public async Task<string> GenerateTextFromAudioAsync(string filePath)
2024-07-30 18:57:32 +00:00
{
string fileExtension = Path.GetExtension(filePath);
2024-08-26 22:24:07 +00:00
if (!Enum.TryParse(fileExtension.TrimStart('.').ToLower(), out AudioType audioType))
2024-07-30 18:57:32 +00:00
{
throw new Exception($"Unsupported audio type: {fileExtension}");
}
2024-08-17 23:34:31 +00:00
2024-08-26 22:24:07 +00:00
using var stream = _audioProcessor.ConvertToStream(filePath);
2024-07-30 18:57:32 +00:00
if (stream == null)
{
throw new Exception($"Failed to convert {fileExtension} to stream");
}
var textResult = new List<SegmentData>();
2024-08-26 22:24:07 +00:00
await foreach (var result in _whisperProcessor.ProcessAsync(stream).ConfigureAwait(false))
2024-07-30 18:57:32 +00:00
{
textResult.Add(result);
}
2024-08-26 22:24:07 +00:00
_whisperProcessor.Dispose();
2024-08-17 23:34:31 +00:00
2024-07-30 18:57:32 +00:00
var audioOutput = new AudioOutput
{
Segments = textResult
};
return audioOutput.ToString();
}
2024-08-26 22:24:07 +00:00
public Task<string> GenerateTextFromAudioAsync(Stream audio, string audioFileName)
{
throw new NotImplementedException();
}
public async Task SetModelName(string model)
{
if (Enum.TryParse(model, true, out GgmlType ggmlType))
{
await LoadWhisperModel(ggmlType);
return;
}
_logger.LogWarning($"Unsupported model type: {model}. Use Tiny model instead!");
await LoadWhisperModel(GgmlType.Tiny);
}
2024-07-30 18:57:32 +00:00
private async Task LoadWhisperModel(GgmlType modelType)
{
try
{
2024-08-17 23:34:31 +00:00
if (!Directory.Exists(MODEL_DIR))
2024-08-26 22:24:07 +00:00
{
2024-08-17 23:34:31 +00:00
Directory.CreateDirectory(MODEL_DIR);
2024-08-26 22:24:07 +00:00
}
2024-07-30 18:57:32 +00:00
2024-08-26 22:24:07 +00:00
var availableModelPaths = Directory.GetFiles(MODEL_DIR, "*.bin").ToArray();
if (availableModelPaths.IsNullOrEmpty())
2024-08-17 23:34:31 +00:00
{
_currentModelPath = SetModelPath(MODEL_DIR, modelType);
await DownloadModel(modelType, _currentModelPath);
}
else
2024-07-30 18:57:32 +00:00
{
2024-08-17 23:34:31 +00:00
var modelFilePath = availableModelPaths.FirstOrDefault(x => Path.GetFileName(x) == $"ggml-{modelType}.bin");
if (modelFilePath == null)
{
_currentModelPath = SetModelPath(MODEL_DIR, modelType);
await DownloadModel(modelType, _currentModelPath);
}
else
{
_currentModelPath = modelFilePath;
}
2024-07-30 18:57:32 +00:00
}
2024-08-17 23:34:31 +00:00
2024-08-26 22:24:07 +00:00
_whisperProcessor = WhisperFactory.FromPath(path: _currentModelPath).CreateBuilder().WithLanguage("auto").Build();
2024-08-17 23:34:31 +00:00
_modelType = modelType;
2024-07-30 18:57:32 +00:00
}
catch (Exception ex)
{
2024-08-26 22:24:07 +00:00
var error = "Failed to load whisper model";
_logger.LogWarning($"${error}: {ex.Message}\r\n{ex.InnerException}");
throw new Exception($"{error}: {ex.Message}");
2024-07-30 18:57:32 +00:00
}
}
2024-08-17 23:34:31 +00:00
private async Task DownloadModel(GgmlType modelType, string modelDir)
2024-07-30 18:57:32 +00:00
{
2024-08-17 23:34:31 +00:00
using var modelStream = await WhisperGgmlDownloader.GetGgmlModelAsync(modelType);
using var fileWriter = File.OpenWrite(modelDir);
await modelStream.CopyToAsync(fileWriter);
2024-07-30 18:57:32 +00:00
}
2024-08-11 16:26:57 +00:00
2024-08-17 23:34:31 +00:00
private string SetModelPath(string rootPath, GgmlType modelType)
{
string currentModelPath = Path.Combine(rootPath, $"ggml-{modelType}.bin");
return currentModelPath;
}
2024-07-30 18:57:32 +00:00
}