Skip to content

Commit

Permalink
Added GetSupportedLanguages method (#245)
Browse files Browse the repository at this point in the history
* Added GetSupportedLanguages method

* Changed GetSupportedLanguages to be static and added CheckLibraryLoaded
  • Loading branch information
sandrohanea authored Oct 30, 2024
1 parent 935b846 commit d15b19c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 8 deletions.
37 changes: 29 additions & 8 deletions Whisper.net/WhisperFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,7 @@ public sealed class WhisperFactory : IDisposable

private WhisperFactory(IWhisperProcessorModelLoader loader, bool delayInit)
{
if (!libraryLoaded.Value.IsSuccess)
{
throw new Exception($"Failed to load native whisper library. Error: {libraryLoaded.Value.ErrorMessage}");
}
CheckLibraryLoaded();

this.loader = loader;
if (!delayInit)
Expand All @@ -57,17 +54,33 @@ private WhisperFactory(IWhisperProcessorModelLoader loader, bool delayInit)
/// <exception cref="Exception"></exception>
public static string? GetRuntimeInfo()
{
if (!libraryLoaded.Value.IsSuccess)
{
throw new Exception($"Failed to load native whisper library. Error: {libraryLoaded.Value.ErrorMessage}");
}
CheckLibraryLoaded();

var systemInfoPtr = libraryLoaded.Value.NativeWhisper!.WhisperPrintSystemInfo();
var systemInfoStr = Marshal.PtrToStringAnsi(systemInfoPtr);
Marshal.FreeHGlobal(systemInfoPtr);
return systemInfoStr;
}

/// <summary>
/// Returns an enumerable of the supported languages.
/// </summary>
/// <returns></returns>
public static IEnumerable<string> GetSupportedLanguages()
{
CheckLibraryLoaded();

for (var i = 0; i < libraryLoaded.Value.NativeWhisper!.Whisper_Lang_Max_Id(); i++)
{
var languagePtr = libraryLoaded.Value.NativeWhisper!.Whisper_Lang_Str(i);
var language = Marshal.PtrToStringAnsi(languagePtr);
if (!string.IsNullOrEmpty(language))
{
yield return language;
}
}
}

/// <summary>
/// Creates a factory that uses the ggml model from a path in order to create <seealso cref="WhisperProcessorBuilder"/>.
/// </summary>
Expand Down Expand Up @@ -131,4 +144,12 @@ public void Dispose()
loader.Dispose();
wasDisposed = true;
}

private static void CheckLibraryLoaded()
{
if (!libraryLoaded.Value.IsSuccess)
{
throw new Exception($"Failed to load native whisper library. Error: {libraryLoaded.Value.ErrorMessage}");
}
}
}
8 changes: 8 additions & 0 deletions tests/Whisper.net.Tests/FactoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ public FactoryTests(TinyModelFixture model)
this.model = model;
}

[Fact]
public void GetSupportedLanguages_ShouldReturnAll()
{
var languages = WhisperFactory.GetSupportedLanguages().ToList();

languages.Should().HaveCount(99);
}

[Fact]
public void CreateBuilder_WithNoModel_ShouldThrow()
{
Expand Down

0 comments on commit d15b19c

Please sign in to comment.