From de6b38c6d96fc3cb2c4797581280963f0224d364 Mon Sep 17 00:00:00 2001 From: Amanda Der Bedrosian Date: Fri, 28 Mar 2025 04:26:22 -0700 Subject: [PATCH] bindings.go : add DetectedLanguage to go bindings (#2947) Adding in DetectedLanguage(), a function to retrieve the detected language that's populated by processing audio. Also adding in a unit test to test the success. Co-authored-by: Amanda Der Bedrosian --- bindings/go/pkg/whisper/context.go | 4 ++++ bindings/go/pkg/whisper/context_test.go | 31 +++++++++++++++++++++++++ bindings/go/pkg/whisper/interface.go | 1 + 3 files changed, 36 insertions(+) diff --git a/bindings/go/pkg/whisper/context.go b/bindings/go/pkg/whisper/context.go index a8061293..cb3d9eb8 100644 --- a/bindings/go/pkg/whisper/context.go +++ b/bindings/go/pkg/whisper/context.go @@ -71,6 +71,10 @@ func (context *context) Language() string { return whisper.Whisper_lang_str(context.params.Language()) } +func (context *context) DetectedLanguage() string { + return whisper.Whisper_lang_str(context.model.ctx.Whisper_full_lang_id()) +} + // Set translate flag func (context *context) SetTranslate(v bool) { context.params.SetTranslate(v) diff --git a/bindings/go/pkg/whisper/context_test.go b/bindings/go/pkg/whisper/context_test.go index 51051481..e98a4c2b 100644 --- a/bindings/go/pkg/whisper/context_test.go +++ b/bindings/go/pkg/whisper/context_test.go @@ -91,3 +91,34 @@ func TestProcess(t *testing.T) { err = context.Process(data, nil, nil, nil) assert.NoError(err) } + +func TestDetectedLanguage(t *testing.T) { + assert := assert.New(t) + + fh, err := os.Open(SamplePath) + assert.NoError(err) + defer fh.Close() + + // Decode the WAV file - load the full buffer + dec := wav.NewDecoder(fh) + buf, err := dec.FullPCMBuffer() + assert.NoError(err) + assert.Equal(uint16(1), dec.NumChans) + + data := buf.AsFloat32Buffer().Data + + model, err := whisper.New(ModelPath) + assert.NoError(err) + assert.NotNil(model) + defer model.Close() + + context, err := model.NewContext() + assert.NoError(err) + + err = context.Process(data, nil, nil, nil) + assert.NoError(err) + + expectedLanguage := "en" + actualLanguage := context.DetectedLanguage() + assert.Equal(expectedLanguage, actualLanguage) +} diff --git a/bindings/go/pkg/whisper/interface.go b/bindings/go/pkg/whisper/interface.go index 2b6a9c8e..e3122c44 100644 --- a/bindings/go/pkg/whisper/interface.go +++ b/bindings/go/pkg/whisper/interface.go @@ -41,6 +41,7 @@ type Context interface { SetTranslate(bool) // Set translate flag IsMultilingual() bool // Return true if the model is multilingual. Language() string // Get language + DetectedLanguage() string // Get detected language SetOffset(time.Duration) // Set offset SetDuration(time.Duration) // Set duration