-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocess.go
72 lines (61 loc) · 1.78 KB
/
process.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
package main
import (
"fmt"
"io"
"os"
"time"
// Package imports
whisper "github.com/ggerganov/whisper.cpp/bindings/go/pkg/whisper"
wav "github.com/go-audio/wav"
)
func Process(model whisper.Model, path string, cb *string) (string, error) {
var data []float32
// Create processing context
context, err := model.NewContext()
if err != nil {
return "app error", err
}
context.SetTranslate(true)
fmt.Printf("\n%s\n", context.SystemInfo())
// Open the file
fmt.Fprintf(os.Stdout, "Loading %q\n", path)
fh, err := os.Open(path)
if err != nil {
return "error opening file", err
}
defer fh.Close()
// Decode the WAV file - load the full buffer
dec := wav.NewDecoder(fh)
if buf, err := dec.FullPCMBuffer(); err != nil {
return "error decoding wav", err
} else if dec.SampleRate != whisper.SampleRate {
return "unsupported sample rate", fmt.Errorf("unsupported sample rate: %d", dec.SampleRate)
} else if dec.NumChans != 1 {
return "unsupported number of channels", fmt.Errorf("unsupported number of channels: %d", dec.NumChans)
} else {
data = buf.AsFloat32Buffer().Data
}
// Process the data
fmt.Fprintf(os.Stdout, " ...processing %q\n", path)
context.ResetTimings()
if err := context.Process(data, nil, nil); err != nil {
return "error processing", err
}
context.PrintTimings()
// Print out the results
return Output(os.Stdout, context, cb)
}
// Output text to terminal
func Output(w io.Writer, context whisper.Context, cb *string) (string, error) {
for {
segment, err := context.NextSegment()
if err == io.EOF {
return "", nil
} else if err != nil {
return "error", err
}
fmt.Fprintf(w, "[%6s->%6s]", segment.Start.Truncate(time.Millisecond), segment.End.Truncate(time.Millisecond))
fmt.Fprintln(w, " ", segment.Text)
*cb += segment.Text + "\n"
}
}