-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslate.go
52 lines (44 loc) · 1.36 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
package subtitle
import (
"context"
"fmt"
"log"
sb "github.com/martinlindhe/subtitles"
"github.com/xwjdsh/fy"
)
const (
TimeFmt = "15:04:05.000"
)
func Translate(path string, fromLang, toLang string, both bool) (*sb.Subtitle, error) {
subtitle, err := Load(path)
if err != nil {
return nil, fmt.Errorf("load subtitle failed: %v", err)
}
newSub := sb.Subtitle{Captions: make([]sb.Caption, len(subtitle.Captions))}
ctx := context.Background()
log.Printf("total %d captions, start translating...", len(subtitle.Captions))
parallel := make(chan bool, 1)
for i, caption := range subtitle.Captions {
parallel <- true
go func() {
defer func() { <-parallel }()
log.Printf("\tseq %v, at %v", caption.Seq, caption.Start.Format(TimeFmt))
var lines []string
for _, line := range caption.Text {
if both {
lines = append(lines, line)
}
res := fy.SogouTranslate(ctx, fy.Request{FromLang: fromLang, ToLang: toLang, Text: line})
if res.Err != nil {
log.Printf("\t\ttranslate failed, seq %v, at %v, err: %v", caption.Seq, caption.Start.Format(TimeFmt), res.Err)
continue
}
log.Printf("\t\t%v -> %v", line, res.Result)
lines = append(lines, res.Result)
}
newCaption := sb.Caption{Seq: caption.Seq, Start: caption.Start, End: caption.End, Text: lines}
newSub.Captions[i] = newCaption
}()
}
return &newSub, nil
}