/
blueMandoTools.go
454 lines (372 loc) · 13.1 KB
/
blueMandoTools.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
package main
import (
"encoding/json"
"fmt"
"github.com/hoisie/mustache"
"github.com/jsoendermann/blueMandoTools/cedict"
"github.com/jsoendermann/blueMandoTools/chinese"
"github.com/jsoendermann/blueMandoTools/moedict"
"github.com/jsoendermann/blueMandoTools/pinyin"
"github.com/jsoendermann/blueMandoTools/zhDicts"
"net/http"
"regexp"
"strings"
)
// This regexp is used to find words in sentences
var findWordsInSentencesRegexp *regexp.Regexp
var findCharInMcdsRegexp *regexp.Regexp
func main() {
fmt.Println("### Welcome to the Blue Mandarin Lab Flash Card Server ###")
err := zhDicts.LoadDb()
if err != nil {
panic(err)
}
defer zhDicts.CloseDb()
err = cedict.Initialize()
if err != nil {
panic(err)
}
err = moedict.Initialize()
if err != nil {
panic(err)
}
findWordsInSentencesRegexp, err = regexp.Compile("\\[(.*?)\\]")
if err != nil {
panic(err)
}
findCharInMcdsRegexp, err = regexp.Compile(clozeBegin + "(.*?)" + clozeEnd)
if err != nil {
panic(err)
}
// Load html files, the array at the end contains the js files to be loaded
homeHtml := mustache.RenderFileInLayout("home.html", layoutFile, map[string]interface{}{})
vocabHtml := mustache.RenderFileInLayout("vocab.html", layoutFile, map[string]interface{}{"jsfiles": []string{"vocab"}})
moeVocabHtml := mustache.RenderFileInLayout("moe-vocab.html", layoutFile, map[string]interface{}{"jsfiles": []string{"moe-vocab"}})
sentencesHtml := mustache.RenderFileInLayout("sentences.html", layoutFile, map[string]interface{}{"jsfiles": []string{"sentences"}})
mcdsHtml := mustache.RenderFileInLayout("mcds.html", layoutFile, map[string]interface{}{"jsfiles": []string{"mcds", "mcds-dict"}})
pinyinifyHtml := mustache.RenderFileInLayout("pinyinify.html", layoutFile, map[string]interface{}{"jsfiles": []string{"pinyinify"}})
settingsHtml := mustache.RenderFileInLayout("settings.html", layoutFile, map[string]interface{}{"jsfiles": []string{"settings"}})
// FIXME set active class in navbar
// Set up the http server
// small helper function (used below)
addStaticHtmlHandler := func(path string, html string) {
http.HandleFunc(path, func(writer http.ResponseWriter, request *http.Request) {
fmt.Fprintf(writer, html)
})
}
addStaticHtmlHandler(homePath, homeHtml)
addStaticHtmlHandler(vocabPath, vocabHtml)
addStaticHtmlHandler(moeVocabPath, moeVocabHtml)
addStaticHtmlHandler(sentencesPath, sentencesHtml)
addStaticHtmlHandler(mcdsPath, mcdsHtml)
addStaticHtmlHandler(pinyinifyPath, pinyinifyHtml)
addStaticHtmlHandler(settingsPath, settingsHtml)
http.HandleFunc(vocabLookupPath, vocabLookupHandler)
http.HandleFunc(moeVocabLookupPath, moeVocabLookupHandler)
http.HandleFunc(sentencesLookupPath, sentencesLookupHandler)
http.HandleFunc(mcdsLookupPath, mcdsLookupHandler)
http.HandleFunc(pinyinifyLookupPath, pinyinifyLookupHandler)
// assets file server
http.Handle(assetsPath, http.FileServer(http.Dir(".")))
http.ListenAndServe(":8080", nil)
}
// This function is responsible for paths of the form
// /vocab/lookup/<word> and returns a json dictionary
// containing the csv to be added to the output text area
// or an "error" field of something other than "nil" if an
// error occured during execution.
func vocabLookupHandler(writer http.ResponseWriter, request *http.Request) {
word := getLastPathComponent(request)
colors := getColors(request)
fmt.Println("vocabLookupHandler: " + word)
// search the db for records (simp first, if unsuccessful, try trad)
// and send errors back to client if any occur
records, err := cedict.FindRecords(word, chinese.Simp)
if err != nil {
fmt.Fprint(writer, `{"error": "`+err.Error()+`", "word": "`+word+`"}`)
return
}
if len(records) == 0 {
records, err = cedict.FindRecords(word, chinese.Trad)
if err != nil {
fmt.Fprint(writer, `{"error": "`+err.Error()+`", "word": "`+word+`"}`)
return
}
}
if len(records) == 0 {
fmt.Fprint(writer, `{"error": "No matches found", "word": "`+word+`"}`)
return
}
// this string has the same number of characters as the word.
// in places where the simplified and the traditional characters
// are the same, it has a space, otherwise it has the simplified character
simpChars := ""
tradChars := ""
for is, cs := range records[0].Simp {
for it, ct := range records[0].Trad {
if is == it {
if cs == ct {
simpChars += string('\u3000')
tradChars += string('\u3000')
} else {
simpChars += string(cs)
tradChars += string(ct)
}
}
}
}
// construct csv row
var output string
output += records[0].Trad
output += "\t"
output += records[0].Simp
output += "\t"
// This dot is necessary because Anki trims whitespace when importing.
// For more details, see the card layout of the shengci deck
output += "." + tradChars
output += "\t"
output += "." + simpChars
output += "\t"
for _, record := range records {
output += pinyin.Num2DiaCol(record.Pinyin, colors, " ")
// Add another real space character at the end
// to make the line break between pinyin and definition on small screens
output += " "
output += record.English
output += "<br />"
}
// use json.Marshal with an anonymous variable to escape the \t and " characters
// in the response
j, err := json.Marshal(map[string]interface{}{
"error": "nil",
"csv": output,
})
if err != nil {
fmt.Fprint(writer, `{"error": "`+err.Error()+`", "word": "`+word+`"}`)
return
}
fmt.Fprint(writer, string(j))
}
func moeVocabLookupHandler(writer http.ResponseWriter, request *http.Request) {
word := getLastPathComponent(request)
colors := getColors(request)
fmt.Println("moeVocabLookupHandler: " + word)
// convert to trad
tradWord, err := cedict.Simp2Trad(word)
if err != nil {
fmt.Fprint(writer, `{"error": "`+err.Error()+`", "word": "`+word+`"}`)
return
}
moeEntry, err := moedict.FindEntry(tradWord)
if moeEntry == nil {
fmt.Fprint(writer, `{"error": "No matches found", "word": "`+word+`"}`)
return
}
if err != nil {
fmt.Fprint(writer, `{"error": "`+err.Error()+`", "word": "`+word+`"}`)
return
}
// construct csv row
var output string
output += tradWord
output += "\t"
output += moeEntry.ToHTML(colors)
// use json.Marshal with an anonymous variable to escape the \t and " characters
// in the response
j, err := json.Marshal(map[string]interface{}{
"error": "nil",
"csv": output,
})
if err != nil {
fmt.Fprint(writer, `{"error": "`+err.Error()+`", "word": "`+word+`"}`)
return
}
fmt.Fprint(writer, string(j))
}
func convertLookupHandler(writer http.ResponseWriter, request *http.Request) {} //TODO
func sentencesLookupHandler(writer http.ResponseWriter, request *http.Request) {
sentence := getLastPathComponent(request)
colors := getColors(request)
fmt.Println("sentencesLookupHandler: " + string([]rune(sentence)[0:10]) + "。。。")
// get words in sentence
wordsRaw := findWordsInSentencesRegexp.FindAllStringSubmatch(sentence, -1)
words := make([]string, len(wordsRaw))
for i, w := range wordsRaw {
words[i] = w[1]
}
charSet := cedict.DetermineCharSet(sentence)
moeEntries, err := findMoeEntriesForWords(words, charSet)
if err != nil {
fmt.Fprint(writer, `{"error": "`+err.Error()+`", "sentence": "`+sentence+`"}`)
return
}
cedictRecords := make([]cedict.Record, 0)
for _, word := range words {
records, err := cedict.FindRecords(word, charSet)
if err != nil {
fmt.Fprint(writer, `{"error": "`+err.Error()+`", "sentence": "`+sentence+`"}`)
return
}
for _, record := range records {
cedictRecords = append(cedictRecords, record)
}
}
// construct csv row
var output string
var outputSentence string
outputSentence = strings.Replace(sentence, "[", "", -1)
outputSentence = strings.Replace(outputSentence, "]", "", -1)
output += outputSentence
output += "\t"
for _, moeEntry := range moeEntries {
output += moeEntry.ToHTML(colors)
output += "<br>"
}
output += "\t"
for _, cedictRecord := range cedictRecords {
output += cedictRecord.ToHTML(colors)
output += "<br>"
}
// This adds an additional field for the audio file
output += "\t"
// This is necessary for Anki to recognise all fields
output += " "
// TODO turn this into a function
// use json.Marshal with an anonymous variable to escape the \t and " characters
// in the response
j, err := json.Marshal(map[string]interface{}{
"error": "nil",
"csv": output,
})
if err != nil {
fmt.Fprint(writer, `{"error": "`+err.Error()+`", "sentence": "`+sentence+`"}`)
return
}
fmt.Fprint(writer, string(j))
}
func mcdsLookupHandler(writer http.ResponseWriter, request *http.Request) {
text := getLastPathComponent(request)
text = strings.Replace(text, "@SLASH@", "/", -1)
text = strings.Replace(text, "\n", "<br />", -1)
text = strings.Replace(text, "\t", " ", -1)
notes := request.FormValue("notes")
notes = strings.Replace(notes, "@SLASH@", "/", -1)
notes = strings.Replace(notes, "\n", "<br />", -1)
notes = strings.Replace(notes, "\t", " ", -1)
charsRaw := request.FormValue("chars")
charsArrayRaw := strings.Split(charsRaw, " ")
// Construct new slice without empty strings
chars := make([]string, 0)
for _, char := range charsArrayRaw {
if char != "" {
chars = append(chars, char)
}
}
colors := getColors(request)
charSet := cedict.DetermineCharSet(text)
splitText, err := chinese.SplitChineseTextIntoWords(text, charSet)
if err != nil {
fmt.Fprint(writer, `{"error": "`+err.Error()+`}`)
return
}
var output string
// Go through all chars to be clozed. Every iteration adds one line to the output var (i.e. one card)
for _, char := range chars {
var front, back string
wordsToBeLookedUp := make([]string, 0)
// This loop goes through all words in the text. This could be optimised by only going
// through the text once and constructing all cards simultaneously
for _, wordInText := range splitText {
indexOfChar := strings.Index(wordInText, char)
if indexOfChar == -1 {
front += wordInText
back += wordInText
} else {
front += strings.Replace(wordInText, char, clozeBegin + clozeChar + clozeEnd, -1)
back += strings.Replace(wordInText, char, clozeBegin + char + clozeEnd, -1)
wordsToBeLookedUp = append(wordsToBeLookedUp, wordInText)
}
}
// Fine unique words to be looked up in moedict
wordsToBeLookedUnique := make([]string, 0)
for _, word := range wordsToBeLookedUp {
alreadyInWordsToBeLookedUpUnique := false
for _, wordUnique := range wordsToBeLookedUnique {
if word == wordUnique {
alreadyInWordsToBeLookedUpUnique = true
}
}
if !alreadyInWordsToBeLookedUpUnique {
wordsToBeLookedUnique = append(wordsToBeLookedUnique, word)
}
}
cedictRecords := make([]cedict.Record,0)
for _, wordToBeLookedUpInCedict := range wordsToBeLookedUnique {
records, _ := cedict.FindRecords(wordToBeLookedUpInCedict, charSet)
for _, record := range records {
cedictRecords = append(cedictRecords, record)
}
}
moeEntries, err := findMoeEntriesForWords(wordsToBeLookedUnique, charSet)
if err != nil {
fmt.Fprint(writer, `{"error": "`+err.Error()+`}`)
return
}
output += front
output += "\t"
output += back
output += "\t"
output += notes
output += "\t"
for _, moeEntry := range moeEntries {
output += moeEntry.ToHTML(colors)
output += "<br>"
}
output += "\t"
for _, cr := range cedictRecords {
output += cr.ToHTML(colors)
output += "<br>"
}
output += "\n"
}
// TODO turn this into a function
// use json.Marshal with an anonymous variable to escape the \t and " characters
// in the response
j, err := json.Marshal(map[string]interface{}{
"error": "nil",
"result": output,
})
if err != nil {
fmt.Fprint(writer, `{"error": "`+err.Error()+`}`)
return
}
fmt.Fprint(writer, string(j))
}
func pinyinifyLookupHandler(writer http.ResponseWriter, request *http.Request) {
text := getLastPathComponent(request)
charSet := cedict.DetermineCharSet(text)
splitText, err := chinese.SplitChineseTextIntoWords(text, charSet)
if err != nil {
fmt.Fprint(writer, `{"error": "`+err.Error()+`}`)
return
}
output := ""
for _, word := range splitText {
records, _ := cedict.FindRecords(word, charSet)
if len(records) > 0 {
output += records[0].Pinyin
} else {
output += word
}
output += " "
}
j, err := json.Marshal(map[string]interface{}{
"error": "nil",
"result": output,
})
if err != nil {
fmt.Fprint(writer, `{"error": "`+err.Error()+`}`)
return
}
fmt.Fprint(writer, string(j))
}