-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslate.go
98 lines (72 loc) · 1.75 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
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
package main
import (
"strings"
"time"
log "github.com/sirupsen/logrus"
"gitgud.io/softashell/comfy-translator/translator"
)
func translate(req translator.Request) string {
if len(strings.TrimSpace(req.Text)) < 1 {
return req.Text
}
start := time.Now()
var err error
var found bool
var out, source string
// Checks if there are pending translation jobs for current request and wait for them to be completed
if ch, wait := q.Join(req); wait {
out := <-ch
log.WithFields(log.Fields{
"time": time.Since(start),
"source": "queue",
}).Infof("%q -> %q", req.Text, out)
return out
}
for _, t := range translators {
source = t.Name()
log.Debugf("Translating with %s", source)
out, found, err = c.Get(source, req.Text)
if found {
source = source + "(cache)"
// cached error
if err != nil {
log.Warnf("%s: %s", source, err)
continue
}
// found translation with no errors
break
}
if !t.Enabled() {
continue
}
out, err = t.Translate(&req)
if err != nil {
log.Warnf("%s: %s", source, err)
if err := c.Put(source, req.Text, out, err); err != nil {
log.Warnf("%s: %s", source, err)
}
continue
}
if len(out) > 0 {
err = c.Put(source, req.Text, out, nil)
if err != nil {
log.WithFields(log.Fields{
"err": err,
}).Errorf("Failed to save result to %s cache", source)
}
}
break
}
out = matchWhitespace(out, req.Text)
// Notify waiting requests that we did the job
q.Push(req, out)
if len(out) < 1 {
// TODO: Return original text or try to handle error in handler
log.Errorf("All services failed to translate %q", req.Text)
}
log.WithFields(log.Fields{
"time": time.Since(start),
"source": source,
}).Infof("%q -> %q", req.Text, out)
return out
}