-
Notifications
You must be signed in to change notification settings - Fork 4
/
Whisper.go
95 lines (85 loc) · 1.79 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
type Response struct {
Text string `json:"text"`
}
func Whisper(pathToFind string) string {
url := "https://api.openai.com/v1/audio/transcriptions"
method := "POST"
payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
file, errFile1 := os.Open(pathToFind)
defer func(file *os.File) {
err := file.Close()
if err != nil {
log.Printf("Error closing file: %v", err)
}
}(file)
part1,
errFile1 := writer.CreateFormFile("file", filepath.Base(pathToFind))
_, errFile1 = io.Copy(part1, file)
if errFile1 != nil {
log.Println(errFile1)
return ""
}
_ = writer.WriteField("model", "whisper-1")
err := writer.Close()
if err != nil {
log.Println(err)
return ""
}
client := &http.Client{}
req, err := http.NewRequest(method, url, payload)
if err != nil {
log.Println(err)
return ""
}
openAi := os.Getenv("OPENAI")
req.Header.Add("Authorization", "Bearer "+openAi)
req.Header.Set("Content-Type", writer.FormDataContentType())
res, err := client.Do(req)
if err != nil {
log.Println(err)
return ""
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Printf("Error closing body: %v", err)
}
}(res.Body)
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Println(err)
return ""
}
text, err := getTextFromJSON(body)
if err != nil {
log.Println(err)
return ""
}
fmt.Println(text)
return text
}
func getTextFromJSON(rawJSON []byte) (string, error) {
// unmarshal the JSON data into the struct
var response Response
err := json.Unmarshal(rawJSON, &response)
if err != nil {
log.Println(err)
return "", err
}
// return the value of the "text" field
return response.Text, nil
}