-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiow.go
297 lines (254 loc) · 5.7 KB
/
iow.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strings"
)
const ApiUri = "https://www.googleapis.com/language/translate/v2"
const ConfigPath = "./.config"
func main() {
args := GetArgs()
if (args.List) {
ListLanguages()
return
}
config := GetConfig()
before := FindWords(args.Text)
// Nothing to translate
if len(before) == 0 {
fmt.Println(args.Text)
return
}
after := TranslateWords(before, config, args)
fmt.Println(ReplaceWords(args.Text, before, after))
return
}
/********** Translation **********/
func FindWords(text string) []string {
// Find all words to translate (in format "[...]")
re := regexp.MustCompile("\\[[^\\[\\]]*\\]")
return re.FindAllString(text, -1)
}
func TranslateWords(words []string, config *Config, args *Args) []string {
after := make([]string, len(words))
var source, target string
if (args.Source != "") {
source = args.Source
} else {
source = config.Source
}
if (args.Target != "") {
target = args.Target
} else {
target = config.Target
}
body := CallApi(source, target, words)
for i, translation := range body.Data.Translations {
after[i] = translation.TranslatedText
}
return after
}
func ReplaceWords(text string, before, after []string) string {
for i, word := range before {
text = strings.Replace(text, word, after[i], -1)
}
return text
}
/********** API **********/
type Body struct {
Data *TranslationsResponse `json:"data"`
}
type TranslationsResponse struct {
Translations []*TranslationsResource `json:"translations,omitempty"`
}
type TranslationsResource struct {
TranslatedText string `json:"translatedText,omitempty"`
}
func CallApi(source, target string, words []string) *Body {
config := GetConfig()
res, _ := http.Get(MakeApiUri(config.ApiKey, source, target, words))
body := new(Body)
json.NewDecoder(res.Body).Decode(&body)
return body
}
func MakeApiUri(key, source, target string, words []string) string {
uri := ApiUri
uri += "?key=" + key
uri += "&source=" + source
uri += "&target=" + target
for _, word := range words {
// Remove "[" and "]"
uri += "&q=" + word[1:len(word)-1]
}
return uri
}
/********** Arguments **********/
type Args struct {
Source string
Target string
Text string
List bool
}
func GetArgs() *Args {
args := new(Args)
flag.StringVar(&args.Source, "s", "", "Set source language")
flag.StringVar(&args.Target, "t", "", "Set target language")
flag.BoolVar(&args.List, "l", false, "List supported languages")
flag.Parse()
args.Text = flag.Arg(0)
return args
}
/********** Config **********/
type Config struct {
ApiKey string `json:"api_key"`
Source string `json:"src_lang"`
Target string `json:"tar_lang"`
}
func GetConfig() *Config {
if _, err := os.Stat(ConfigPath); os.IsNotExist(err) {
SetupConfig()
} else if err != nil {
log.Fatalf("Error reading config file")
}
raw, err := ioutil.ReadFile(ConfigPath)
if err != nil {
log.Fatalf("Error reading config file")
}
config := new(Config)
if err = json.Unmarshal(raw, config); err != nil {
log.Fatalf("Error parsing config file")
}
return config
}
func SetupConfig() error {
config := new(Config)
config.ApiKey = GetInput("Google API Key: ")
config.Source = GetInput("Default source language: ")
config.Target = GetInput("Default target language: ")
buf, _ := json.Marshal(config)
return ioutil.WriteFile(ConfigPath, buf, 0644)
}
/********** Auxiliary **********/
func GetInput(prompt string) string {
fmt.Print(prompt)
reader := bufio.NewReader(os.Stdin)
buf, err := reader.ReadString('\n')
if err != nil {
log.Fatalf("Error reading input: %v", err)
}
return strings.Trim(buf, "\n")
}
func ListLanguages() {
fmt.Print(`Supported languages:
af Afrikaans
am Amharic
ar Arabic
az Azeerbaijani
be Belarusian
bg Bulgarian
bn Bengali
bs Bosnian
ca Catalan
ceb Cebuano
co Corsican
cs Czech
cy Welsh
da Danish
de German
el Greek
en English
eo Esperanto
es Spanish
et Estonian
eu Basque
fa Persian
fi Finnish
fr French
fy Frisian
ga Irish
gd Scots Gaelic
gl Galician
gu Gujarati
ha Hausa
haw Hawaiian
hi Hindi
hmn Hmong
hr Croatian
ht Haitian Creole
hu Hungarian
hy Armenian
id Indonesian
ig Igbo
is Icelandic
it Italian
iw Hebrew
ja Japanese
jw Javanese
ka Georgian
kk Kazakh
km Khmer
kn Kannada
ko Korean
ku Kurdish
ky Kyrgyz
la Latin
lb Luxembourgish
lo Lao
lt Lithuanian
lv Latvian
ma Punjabi
mg Malagasy
mi Maori
mk Macedonian
ml Malayalam
mn Mongolian
mr Marathi
ms Malay
mt Maltese
my Burmese
ne Nepali
nl Dutch
no Norwegian
ny Chichewa
pl Polish
ps Pashto
pt Portuguese
ro Romanian
ru Russian
sd Sindhi
si Sinhala
sk Slovak
sl Slovenian
sm Samoan
sn Shona
so Somali
sq Albanian
sr Serbian
st Sesotho
su Sundanese
sv Swedish
sw Swahili
ta Tamil
te Telugu
tg Tajik
th Thai
tl Filipino
tr Turkish
uk Ukrainian
ur Urdu
uz Uzbek
vi Vietnamese
xh Xhosa
yi Yiddish
yo Yoruba
zh Chinese
zu Zulu
`)
}