-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstt.go
More file actions
90 lines (78 loc) · 2.01 KB
/
stt.go
File metadata and controls
90 lines (78 loc) · 2.01 KB
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
package yask
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strconv"
)
// STTConfigDefault returns STTConfig with default parameters
func STTConfigDefault(yaFolderID, yaAPIKey string, data io.Reader) *STTConfig {
return &STTConfig{
Lang: "ru-RU",
Topic: "general",
ProfanityFilter: false,
Format: FormatLPCM,
Rate: Rate8k,
YaFolderID: yaFolderID,
YaAPIKey: yaAPIKey,
Data: data,
}
}
// STTConfig is config for speech to text methods
type STTConfig struct {
Lang string
Topic string
ProfanityFilter bool
Format string
Rate int
YaFolderID string
YaAPIKey string
Data io.Reader
}
// uri returns url with get parameters for http request
func (s *STTConfig) uri() string {
vars := url.Values{
"lang": []string{s.Lang},
"topic": []string{s.Topic},
"profanityFilter": []string{strconv.FormatBool(s.ProfanityFilter)},
"format": []string{s.Format},
"sampleRateHertz": []string{strconv.FormatInt(int64(s.Rate), 10)},
"folderId": []string{s.YaFolderID},
}
url := fmt.Sprintf("%v?%v", YaSTTUrl, vars.Encode())
return url
}
// SpeechToTextShort returns text from a PCM or OGG sound stream using the service Yandex Speech Kit
func SpeechToTextShort(conf *STTConfig) (string, error) {
req, err := http.NewRequest(
"POST",
conf.uri(),
conf.Data,
)
if err != nil {
return "", err
}
req.Header.Set("Transfer-encoding", "chunked")
req.Header.Set("Authorization", fmt.Sprintf("Api-Key %v", conf.YaAPIKey))
cl := new(http.Client)
resp, err := cl.Do(req)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
return "", unmarshallYaError(resp.Body)
}
rSource, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
m := make(map[string]interface{})
if err = json.Unmarshal(rSource, &m); err != nil {
return "", err
}
result := fmt.Sprint(m["result"])
return result, nil
}