-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
253 lines (205 loc) · 5.87 KB
/
main.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
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"cloud.google.com/go/translate"
"golang.org/x/text/language"
)
func translateText(sourceLanguage, targetLanguage string, text []string) ([]string, error) {
ctx := context.Background()
var translated []string
lang, err := language.Parse(targetLanguage)
target, err2 := language.Parse(sourceLanguage)
if err != nil {
return translated, fmt.Errorf("language.Parse: %v", err)
}
if err2 != nil {
return translated, fmt.Errorf("language.Parse: %v", err)
}
client, err := translate.NewClient(ctx)
if err != nil {
return translated, err
}
defer client.Close()
resp, err := client.Translate(ctx, text, lang, &translate.Options{
Source: target,
})
if err != nil {
return translated, fmt.Errorf("translate: %v", err)
}
if len(resp) == 0 {
return translated, fmt.Errorf("translate returned empty response to text: %s", text)
}
for _, translation := range resp {
translated = append(translated, translation.Text)
}
return translated, nil
}
type content map[string]interface{}
func readJson(path string) content {
file, err := os.ReadFile(path)
if err != nil {
panic(err)
}
data := make(content)
err = json.Unmarshal([]byte(file), &data)
if err != nil {
panic(err)
}
return data
}
// get returns the value of a nested key in the map using dot notation.
func (c content) get(query string) interface{} {
keys := strings.Split(query, ".")
for _, key := range keys {
value, ok := c[key]
if !ok {
return nil
}
c, ok = value.(map[string]interface{})
if !ok {
return value
}
}
return c
}
// set sets the value of a nested key in the map using dot notation.
func (c content) set(query string, value interface{}) {
keys := strings.Split(query, ".")
lastKey := keys[len(keys)-1]
for _, key := range keys[:len(keys)-1] {
subData, ok := c[key].(map[string]interface{})
if !ok {
subData = make(map[string]interface{})
c[key] = subData
}
c = subData
}
c[lastKey] = value
}
// keys returns a slice of all keys in the map, with nested keys represented using dot notation.
func (c content) keys() []string {
return c.getSubKeys("", c)
}
// getSubKeys recursively gets all keys in a nested map, with nested keys represented using dot notation.
func (c content) getSubKeys(prefix string, subMap map[string]interface{}) []string {
var keys []string
for key, value := range subMap {
fullKey := fmt.Sprintf("%s%s", prefix, key)
if subSubMap, ok := value.(map[string]interface{}); ok {
subKeys := c.getSubKeys(fmt.Sprintf("%s%s", fullKey, "."), subSubMap)
keys = append(keys, subKeys...)
} else {
keys = append(keys, fullKey)
}
}
return keys
}
// save to json file
func (c content) save(path string) {
// Convert the map to JSON
rawJSON, err := json.MarshalIndent(c, "", " ")
if err != nil {
panic(err)
}
// Replace the Unicode escape sequences with the corresponding characters
jsonString := string(rawJSON)
re := regexp.MustCompile(`\\u([0-9a-fA-F]{4})`)
jsonString = re.ReplaceAllStringFunc(jsonString, func(m string) string {
u, _ := strconv.ParseInt(m[2:], 16, 32)
return string(rune(u))
})
// Write the JSON to a file
err = os.WriteFile(path, []byte(jsonString), 0644)
if err != nil {
panic(err)
}
}
// splitIntoArrays returns 2D Array given maxlength for each item
func splitIntoArrays(strs []string, maxLen int) [][]string {
var result [][]string
for i := 0; i < len(strs); i += maxLen {
end := i + maxLen
if end > len(strs) {
end = len(strs)
}
result = append(result, strs[i:end])
}
return result
}
func fileExists(filePath string) bool {
// Check if the file exists
_, err := os.Stat(filePath)
return err == nil
}
// getKeysNotInArray2 returns the keys in the first array that are not in the second array.
// It takes two string arrays as arguments and returns a new slice of strings containing the keys that are not in the second array.
func getKeysNotInArray2(arr1 []string, arr2 []string) []string {
// Create a map to hold the items in the second array
itemsInArray2 := make(map[string]bool)
for _, item := range arr2 {
itemsInArray2[item] = true
}
// Loop through the first array and add the keys that are not in the second array to a new slice
var result []string
for _, key := range arr1 {
if _, ok := itemsInArray2[key]; !ok {
result = append(result, key)
}
}
return result
}
func main() {
// Parse command-line arguments
inputFile := flag.String("input", "", "Path to the input JSON file")
sourceLanguage := flag.String("source", "en", "Source language code")
targetLanguage := flag.String("target", "", "Target language code")
outputFile := flag.String("output", "output.json", "Path to the output JSON file")
flag.Parse()
// Check that all required arguments are provided
if *inputFile == "" || *targetLanguage == "" {
fmt.Println("Input file or target language missing.")
os.Exit(1)
}
// Check if input file exists.
if !fileExists(*inputFile) {
fmt.Println("Failed to read input file.")
os.Exit(1)
}
input := readJson(*inputFile)
inputKeys := input.keys()
output := make(content)
// Check if output file exists.
if fileExists(*outputFile) {
output = readJson(*outputFile)
// Get only keys in the input file but not in the output file.
// skip translating again the whole file.
inputKeys = getKeysNotInArray2(input.keys(), output.keys())
}
// type.googleapis.com/google.rpc.BadRequest
// Number of text queries > Maximum: 128
splitted := splitIntoArrays(inputKeys, 128)
for i, keys := range splitted {
var values []string
for _, key := range keys {
if str, ok := input.get(key).(string); ok {
values = append(values, str)
}
}
text, err := translateText(*sourceLanguage, *targetLanguage, values)
if err != nil {
panic(err)
}
for i, key := range splitted[i] {
output.set(key, text[i])
}
}
// Save output
output.save(*outputFile)
}