-
Notifications
You must be signed in to change notification settings - Fork 0
/
translate.go
71 lines (57 loc) · 1.63 KB
/
translate.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
package gcp
import (
"bytes"
"encoding/json"
"errors"
"github.com/beauxarts/polyglot"
"net/http"
)
const (
applicationJsonContentType = "application/json"
)
type TranslateRequest struct {
Query []string `json:"q"`
Target string `json:"target,omitempty"`
Format string `json:"format,omitempty"`
Source string `json:"source,omitempty"`
Model string `json:"model,omitempty"`
}
type TranslateResponse struct {
Data TranslateTextResponseList `json:"data"`
}
type TranslateTextResponseList struct {
Translations []TranslateTextResponseTranslation `json:"translations"`
}
type TranslateTextResponseTranslation struct {
DetectedSourceLanguage string `json:"detectedSourceLanguage"`
Model string `json:"model"`
TranslatedText string `json:"translatedText"`
}
func Translate(hc *http.Client, query []string, target string, format polyglot.TranslateFormat, source, model, key string) ([]TranslateTextResponseTranslation, error) {
if len(query) > 128 {
return nil, errors.New("the maximum number of query strings is 128")
}
treq := &TranslateRequest{
Query: query,
Target: target,
Format: string(format),
Source: source,
Model: model,
}
data, err := json.Marshal(treq)
if err != nil {
return nil, err
}
tu := TranslateUrl(key)
resp, err := hc.Post(tu.String(), applicationJsonContentType, bytes.NewReader(data))
defer resp.Body.Close()
if err != nil {
return nil, err
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return nil, errors.New(resp.Status)
}
var tresp *TranslateResponse
err = json.NewDecoder(resp.Body).Decode(&tresp)
return tresp.Data.Translations, err
}