Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix(DeepL): support long text #156

Merged
merged 1 commit into from
Feb 22, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions translate/deepl/deepl.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,15 @@ func (dpl *DeepL) Translate(q, source, target string) (result string, err error)
var resp *http.Response
if resp, err = fetch.Post(
apiURL,
fetch.WithURLEncodedBody(map[string]string{
"text": q,
fetch.WithJSONBody(map[string]any{
"text": splitTextsAfter(q, "\n", ".", "。"),
"source_lang": parseToDeeplSupportedLanguage(source),
"target_lang": parseToDeeplSupportedLanguage(target),
"split_sentences": "0", // disable sentence split
}),
fetch.WithRaiseForStatus(true),
fetch.WithHeader("Authorization", "DeepL-Auth-Key "+dpl.APIKey),
fetch.WithHeader("Content-Type", "application/x-www-form-urlencoded"),
fetch.WithHeader("Content-Type", "application/json"),
); err != nil {
return
}
Expand All @@ -50,11 +50,28 @@ func (dpl *DeepL) Translate(q, source, target string) (result string, err error)
} `json:"translations"`
}{}
if err = json.NewDecoder(resp.Body).Decode(&data); err == nil {
result = data.Translations[0].Text
sb := &strings.Builder{}
for _, tl := range data.Translations {
sb.WriteString(tl.Text)
}
result = sb.String()
}
return
}

func splitTextsAfter(text string, seps ...string) []string {
results := []string{text}
for _, sep := range seps {
var temp []string
for _, str := range results {
parts := strings.SplitAfter(str, sep)
temp = append(temp, parts...)
}
results = temp
}
return results
}

func parseToDeeplSupportedLanguage(lang string) string {
lang = strings.ToUpper(lang)
switch lang {
Expand Down
Loading