-
Notifications
You must be signed in to change notification settings - Fork 0
/
whisper.go
79 lines (64 loc) · 1.43 KB
/
whisper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package whisper
import (
"fmt"
"os"
"os/exec"
"github.com/ggerganov/whisper.cpp/bindings/go/pkg/whisper"
wav "github.com/go-audio/wav"
)
func sh(c string) (string, error) {
cmd := exec.Command("/bin/sh", "-c", c)
cmd.Env = os.Environ()
o, err := cmd.CombinedOutput()
return string(o), err
}
// AudioToWav converts audio to wav for transcribe. It bashes out to ffmpeg
// TODO: use https://github.com/mccoyst/ogg?
func AudioToWav(src, dst string) error {
out, err := sh(fmt.Sprintf("ffmpeg -i %s -format s16le -ar 16000 -ac 1 -acodec pcm_s16le %s", src, dst))
if err != nil {
return fmt.Errorf("error: %w out: %s", err, out)
}
return nil
}
func Transcribe(modelpath, audiopath, language string) (string, error) {
// Open samples
fh, err := os.Open(audiopath)
if err != nil {
return "", err
}
defer fh.Close()
// Read samples
d := wav.NewDecoder(fh)
buf, err := d.FullPCMBuffer()
if err != nil {
return "", err
}
data := buf.AsFloat32Buffer().Data
// Load the model
model, err := whisper.New(modelpath)
if err != nil {
return "", err
}
defer model.Close()
// Process samples
context, err := model.NewContext()
if err != nil {
return "", err
}
if language != "" {
context.SetLanguage(language)
}
if err := context.Process(data, nil); err != nil {
return "", err
}
text := ""
for {
segment, err := context.NextSegment()
if err != nil {
break
}
text += segment.Text
}
return text, nil
}