mirror of
https://github.com/OwO-Network/DeepLX.git
synced 2026-12-01 14:57:52 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0f2b50dd69 | ||
|
|
ee1114252e | ||
|
|
b28dcd4958 | ||
|
|
4fb2759d48 | ||
|
|
7269cf615a | ||
|
|
83f97d336d | ||
|
|
10f66b9484 | ||
|
|
c9f7467d0e | ||
|
|
97001438d1 |
@@ -63,12 +63,36 @@ Download the binary for your platform from [Releases](https://github.com/OwO-Net
|
|||||||
|
|
||||||
### Translate
|
### Translate
|
||||||
|
|
||||||
|
`text` accepts either a single string or an array of strings. A string is answered with a string in `data`; an array is answered with a position-aligned array of the same length, and the whole batch travels in a single upstream request.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
# Single text
|
||||||
curl -X POST http://localhost:1188/translate \
|
curl -X POST http://localhost:1188/translate \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d '{"text": "Hello, world!", "source_lang": "EN", "target_lang": "ZH"}'
|
-d '{"text": "Hello, world!", "source_lang": "EN", "target_lang": "ZH"}'
|
||||||
```
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"alternatives":null,"code":200,"data":"你好,世界!","id":123,"method":"Free","source_lang":"EN","target_lang":"ZH"}
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Batch: one entry per text, answers come back in the same order
|
||||||
|
curl -X POST http://localhost:1188/translate \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"text": ["Hello, world!", "Good morning"], "source_lang": "EN", "target_lang": "ZH"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"alternatives":null,"code":200,"data":["你好,世界!","早上好"],"id":123,"method":"Free","source_lang":"EN","target_lang":"ZH"}
|
||||||
|
```
|
||||||
|
|
||||||
|
Batch limits and failure modes:
|
||||||
|
|
||||||
|
- The anonymous limit is **1500 characters for the whole request**, counted in UTF-16 code units — what JavaScript's `String.prototype.length` reports, so a CJK character costs 1 and an astral one (emoji, historic scripts) costs 2 — across every text in the array, not 1500 per text. A batch over that total is rejected with `413` and `text exceeds maximum length: N characters (anonymous oneshot limit is 1500)`, so a large batch has to be chunked by total length rather than by segment count. There is no separate cap on the number of texts.
|
||||||
|
- A blank text — empty, or nothing but whitespace — is answered with itself and never sent, so a blank line in a segmented document keeps its place instead of failing the request. `"text": []` is answered with `{"data": []}`; a body with no `text` field at all, or `"text": null`, is rejected with `400 {"code":400,"message":"Invalid request payload"}`.
|
||||||
|
- A batch is all-or-nothing: if DeepL returns a different number of translations or leaves one of them empty, the request fails with `503 {"code":503,"message":"Translation failed"}` instead of answering with placeholders or a shorter, misaligned array.
|
||||||
|
|
||||||
## Discussion Group
|
## Discussion Group
|
||||||
[Telegram Group](https://t.me/+8KDGHKJCxEVkNzll)
|
[Telegram Group](https://t.me/+8KDGHKJCxEVkNzll)
|
||||||
|
|
||||||
|
|||||||
+76
-10
@@ -13,6 +13,8 @@
|
|||||||
package service
|
package service
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -74,6 +76,52 @@ type PayloadAPI struct {
|
|||||||
TagHandling string `json:"tag_handling"`
|
TagHandling string `json:"tag_handling"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PayloadTranslate is the request body of POST /translate. Unlike PayloadFree
|
||||||
|
// (shared with the Pro endpoint), `text` accepts either a single string or an
|
||||||
|
// array of strings.
|
||||||
|
type PayloadTranslate struct {
|
||||||
|
Text PayloadText `json:"text"`
|
||||||
|
SourceLang string `json:"source_lang"`
|
||||||
|
TargetLang string `json:"target_lang"`
|
||||||
|
TagHandling string `json:"tag_handling"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// PayloadText is the `text` field of POST /translate, in either documented
|
||||||
|
// shape: a bare JSON string or an array of strings. Both are normalized to
|
||||||
|
// Texts, and Batch records which shape the caller used so the response can
|
||||||
|
// mirror it. Any other shape (a number, an object, an array holding
|
||||||
|
// non-strings) fails the payload decode, which the handler reports as
|
||||||
|
// 400 Invalid request payload; null names no text, like a body without the key.
|
||||||
|
type PayloadText struct {
|
||||||
|
Texts []string
|
||||||
|
Batch bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalJSON implements json.Unmarshaler.
|
||||||
|
func (p *PayloadText) UnmarshalJSON(data []byte) error {
|
||||||
|
trimmed := bytes.TrimSpace(data)
|
||||||
|
if len(trimmed) > 0 && trimmed[0] == '[' {
|
||||||
|
var texts []string
|
||||||
|
if err := json.Unmarshal(trimmed, &texts); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p.Texts, p.Batch = texts, true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// A JSON null names no text: leave the zero value, so Texts stays nil.
|
||||||
|
if string(trimmed) == "null" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var text string
|
||||||
|
if err := json.Unmarshal(data, &text); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p.Texts, p.Batch = []string{text}, false
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func Router(cfg *Config) *gin.Engine {
|
func Router(cfg *Config) *gin.Engine {
|
||||||
// Set Proxy
|
// Set Proxy
|
||||||
proxyURL := os.Getenv("PROXY")
|
proxyURL := os.Getenv("PROXY")
|
||||||
@@ -107,7 +155,7 @@ func Router(cfg *Config) *gin.Engine {
|
|||||||
|
|
||||||
// Free API endpoint, No Pro Account required
|
// Free API endpoint, No Pro Account required
|
||||||
r.POST("/translate", authMiddleware(cfg), func(c *gin.Context) {
|
r.POST("/translate", authMiddleware(cfg), func(c *gin.Context) {
|
||||||
req := PayloadFree{}
|
req := PayloadTranslate{}
|
||||||
if err := c.BindJSON(&req); err != nil {
|
if err := c.BindJSON(&req); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{
|
c.JSON(http.StatusBadRequest, gin.H{
|
||||||
"code": http.StatusBadRequest,
|
"code": http.StatusBadRequest,
|
||||||
@@ -116,9 +164,20 @@ func Router(cfg *Config) *gin.Engine {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A body without `text` never named a text to translate, which is a
|
||||||
|
// payload error. `"text": []` names a list that happens to be empty,
|
||||||
|
// and is answered with an empty list, so it is not caught here.
|
||||||
|
if req.Text.Texts == nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{
|
||||||
|
"code": http.StatusBadRequest,
|
||||||
|
"message": "Invalid request payload",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
sourceLang := req.SourceLang
|
sourceLang := req.SourceLang
|
||||||
targetLang := req.TargetLang
|
targetLang := req.TargetLang
|
||||||
translateText := req.TransText
|
texts := req.Text.Texts
|
||||||
tagHandling := req.TagHandling
|
tagHandling := req.TagHandling
|
||||||
|
|
||||||
proxyURL := cfg.Proxy
|
proxyURL := cfg.Proxy
|
||||||
@@ -131,7 +190,7 @@ func Router(cfg *Config) *gin.Engine {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := translate.TranslateByDLX(sourceLang, targetLang, translateText, tagHandling, proxyURL, "")
|
result, err := translate.TranslateByDLX(sourceLang, targetLang, texts, tagHandling, proxyURL, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Translation failed: %s", err)
|
log.Printf("Translation failed: %s", err)
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{
|
c.JSON(http.StatusInternalServerError, gin.H{
|
||||||
@@ -142,15 +201,22 @@ func Router(cfg *Config) *gin.Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if result.Code == http.StatusOK {
|
if result.Code == http.StatusOK {
|
||||||
c.JSON(http.StatusOK, gin.H{
|
response := gin.H{
|
||||||
"code": http.StatusOK,
|
"code": http.StatusOK,
|
||||||
"id": result.ID,
|
"id": result.ID,
|
||||||
"data": result.Data,
|
|
||||||
"alternatives": result.Alternatives,
|
"alternatives": result.Alternatives,
|
||||||
"source_lang": result.SourceLang,
|
"source_lang": result.SourceLang,
|
||||||
"target_lang": result.TargetLang,
|
"target_lang": result.TargetLang,
|
||||||
"method": result.Method,
|
"method": result.Method,
|
||||||
})
|
}
|
||||||
|
// Mirror the request: a string in `text` answers with a string
|
||||||
|
// in `data`, an array answers with a position-aligned array.
|
||||||
|
if req.Text.Batch {
|
||||||
|
response["data"] = result.Data
|
||||||
|
} else {
|
||||||
|
response["data"] = result.Data[0]
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, response)
|
||||||
} else {
|
} else {
|
||||||
c.JSON(result.Code, gin.H{
|
c.JSON(result.Code, gin.H{
|
||||||
"code": result.Code,
|
"code": result.Code,
|
||||||
@@ -206,7 +272,7 @@ func Router(cfg *Config) *gin.Engine {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := translate.TranslateByDLX(sourceLang, targetLang, translateText, tagHandling, proxyURL, dlSession)
|
result, err := translate.TranslateByDLX(sourceLang, targetLang, []string{translateText}, tagHandling, proxyURL, dlSession)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Translation failed: %s", err)
|
log.Printf("Translation failed: %s", err)
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{
|
c.JSON(http.StatusInternalServerError, gin.H{
|
||||||
@@ -220,7 +286,7 @@ func Router(cfg *Config) *gin.Engine {
|
|||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"code": http.StatusOK,
|
"code": http.StatusOK,
|
||||||
"id": result.ID,
|
"id": result.ID,
|
||||||
"data": result.Data,
|
"data": result.Data[0],
|
||||||
"alternatives": result.Alternatives,
|
"alternatives": result.Alternatives,
|
||||||
"source_lang": result.SourceLang,
|
"source_lang": result.SourceLang,
|
||||||
"target_lang": result.TargetLang,
|
"target_lang": result.TargetLang,
|
||||||
@@ -267,7 +333,7 @@ func Router(cfg *Config) *gin.Engine {
|
|||||||
targetLang = jsonData.TargetLang
|
targetLang = jsonData.TargetLang
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := translate.TranslateByDLX(sourceLang, targetLang, translateText, "", proxyURL, "")
|
result, err := translate.TranslateByDLX(sourceLang, targetLang, []string{translateText}, "", proxyURL, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Translation failed: %s", err)
|
log.Printf("Translation failed: %s", err)
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{
|
c.JSON(http.StatusInternalServerError, gin.H{
|
||||||
@@ -282,7 +348,7 @@ func Router(cfg *Config) *gin.Engine {
|
|||||||
"translations": []map[string]interface{}{
|
"translations": []map[string]interface{}{
|
||||||
{
|
{
|
||||||
"detected_source_language": result.SourceLang,
|
"detected_source_language": result.SourceLang,
|
||||||
"text": result.Data,
|
"text": result.Data[0],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The `text` field of POST /translate accepts either shape; decoding uses the
|
||||||
|
// same encoding/json decoder gin binds request bodies with.
|
||||||
|
func TestPayloadTextUnmarshalJSON(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
payload string
|
||||||
|
wantTexts []string
|
||||||
|
wantBatch bool
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{name: "string", payload: `{"text":"Hello"}`, wantTexts: []string{"Hello"}},
|
||||||
|
{name: "empty string", payload: `{"text":""}`, wantTexts: []string{""}},
|
||||||
|
{name: "array", payload: `{"text":["Hello","Good morning"]}`, wantTexts: []string{"Hello", "Good morning"}, wantBatch: true},
|
||||||
|
{name: "single-element array", payload: `{"text":["Hello"]}`, wantTexts: []string{"Hello"}, wantBatch: true},
|
||||||
|
{name: "empty array", payload: `{"text":[]}`, wantTexts: []string{}, wantBatch: true},
|
||||||
|
{name: "null", payload: `{"text":null}`, wantTexts: nil},
|
||||||
|
{name: "no text field", payload: `{}`, wantTexts: nil},
|
||||||
|
{name: "number", payload: `{"text":1}`, wantErr: true},
|
||||||
|
{name: "object", payload: `{"text":{}}`, wantErr: true},
|
||||||
|
{name: "mixed array", payload: `{"text":["Hello",1]}`, wantErr: true},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
var req PayloadTranslate
|
||||||
|
err := json.NewDecoder(strings.NewReader(tt.payload)).Decode(&req)
|
||||||
|
if (err != nil) != tt.wantErr {
|
||||||
|
t.Fatalf("Decode(%s) error = %v, wantErr %v", tt.payload, err, tt.wantErr)
|
||||||
|
}
|
||||||
|
if tt.wantErr {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if req.Text.Batch != tt.wantBatch {
|
||||||
|
t.Errorf("Batch = %v, want %v", req.Text.Batch, tt.wantBatch)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(req.Text.Texts, tt.wantTexts) {
|
||||||
|
t.Errorf("Texts = %q, want %q", req.Text.Texts, tt.wantTexts)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /translate mirrors the shape it was given, and no shape that carries
|
||||||
|
// text is an error any more — an empty text is answered with itself and an
|
||||||
|
// empty array with an empty array. Every case here is answered (or refused)
|
||||||
|
// before a translation is attempted, so the test never reaches DeepL.
|
||||||
|
func TestTranslateHandlerAnswersEmptyText(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
router := Router(&Config{})
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
payload string
|
||||||
|
wantCode int
|
||||||
|
wantInBody string
|
||||||
|
}{
|
||||||
|
{"empty array", `{"text":[],"target_lang":"EN"}`, http.StatusOK, `"data":[]`},
|
||||||
|
{"empty string", `{"text":"","target_lang":"EN"}`, http.StatusOK, `"data":""`},
|
||||||
|
{"null", `{"text":null,"target_lang":"EN"}`, http.StatusBadRequest, `Invalid request payload`},
|
||||||
|
{"array of empty", `{"text":[""],"target_lang":"EN"}`, http.StatusOK, `"data":[""]`},
|
||||||
|
{"no text field", `{"target_lang":"EN"}`, http.StatusBadRequest, `Invalid request payload`},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
request := httptest.NewRequest(http.MethodPost, "/translate", strings.NewReader(tt.payload))
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
router.ServeHTTP(recorder, request)
|
||||||
|
|
||||||
|
if recorder.Code != tt.wantCode {
|
||||||
|
t.Fatalf("POST /translate %s = %d %s, want %d", tt.payload, recorder.Code, recorder.Body.String(), tt.wantCode)
|
||||||
|
}
|
||||||
|
if !strings.Contains(recorder.Body.String(), tt.wantInBody) {
|
||||||
|
t.Fatalf("POST /translate %s body = %s, want it to contain %s", tt.payload, recorder.Body.String(), tt.wantInBody)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
package translate
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"unicode/utf8"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The anonymous cap is a UTF-16 length, not a rune count: an astral character
|
||||||
|
// is a surrogate pair and costs two units, which is the only place the two
|
||||||
|
// disagree. A rune count understates such a request and lets oneshot answer it
|
||||||
|
// with a bare 400 instead.
|
||||||
|
func TestTextLength(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
text string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{"empty", "", 0},
|
||||||
|
{"ascii", "Hello, world!", 13},
|
||||||
|
{"BMP CJK", "你好", 2},
|
||||||
|
{"highest BMP code point", "\uFFFF", 1},
|
||||||
|
{"lowest astral code point", "\U00010000", 2},
|
||||||
|
{"astral character", "😀", 2},
|
||||||
|
{"astral characters", "😀😀", 4},
|
||||||
|
{"mixed", "a😀b", 4},
|
||||||
|
{"combining mark is two units, not one grapheme", "e\u0301", 2},
|
||||||
|
{"at the limit", strings.Repeat("a", maxFreeTextLength), maxFreeTextLength},
|
||||||
|
{"one past the limit", strings.Repeat("a", maxFreeTextLength+1), maxFreeTextLength + 1},
|
||||||
|
{"astral at the limit", strings.Repeat("😀", maxFreeTextLength/2), maxFreeTextLength},
|
||||||
|
{"astral past the limit", strings.Repeat("😀", maxFreeTextLength/2+1), maxFreeTextLength + 2},
|
||||||
|
{"combining at the limit", strings.Repeat("e\u0301", maxFreeTextLength/2), maxFreeTextLength},
|
||||||
|
{"combining past the limit", strings.Repeat("e\u0301", maxFreeTextLength/2+1), maxFreeTextLength + 2},
|
||||||
|
{"invalid UTF-8 counts one unit per byte", "\xf0\x90\x80", 3},
|
||||||
|
{"invalid UTF-8 mixed with ASCII", "a\xff\xfeb", 4},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
if got := textLength(tt.text); got != tt.want {
|
||||||
|
t.Fatalf("textLength(%q) = %d, want %d", tt.text, got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The guard counts JSON-decoded text, and encoding/json has already replaced
|
||||||
|
// every invalid byte with U+FFFD by then — json.Marshal would replace them
|
||||||
|
// again on the way upstream — so invalid UTF-8 never reaches textLength as
|
||||||
|
// invalid bytes, and the old rune count agreed with it exactly there. Invalid
|
||||||
|
// UTF-8 is therefore not what made the rune count wrong; an astral character
|
||||||
|
// is, which is the one case where the two columns below differ.
|
||||||
|
func TestTextLengthOnJSONDecodedText(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
body string
|
||||||
|
wantText string
|
||||||
|
wantUnits int
|
||||||
|
wantRunes int
|
||||||
|
}{
|
||||||
|
{"invalid UTF-8 in the body", "{\"text\":\"\xf0\x90\x80\"}", "\uFFFD\uFFFD\uFFFD", 3, 3},
|
||||||
|
{"paired surrogate escape", `{"text":"\ud83d\ude00"}`, "😀", 2, 1},
|
||||||
|
{"lone surrogate escape", `{"text":"\ud83d"}`, "\uFFFD", 1, 1},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
var payload struct {
|
||||||
|
Text string `json:"text"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal([]byte(tt.body), &payload); err != nil {
|
||||||
|
t.Fatalf("json.Unmarshal(%q) error = %v", tt.body, err)
|
||||||
|
}
|
||||||
|
if payload.Text != tt.wantText {
|
||||||
|
t.Fatalf("decoded text = %q, want %q", payload.Text, tt.wantText)
|
||||||
|
}
|
||||||
|
if got := textLength(payload.Text); got != tt.wantUnits {
|
||||||
|
t.Fatalf("textLength(%q) = %d, want %d", payload.Text, got, tt.wantUnits)
|
||||||
|
}
|
||||||
|
if got := utf8.RuneCountInString(payload.Text); got != tt.wantRunes {
|
||||||
|
t.Fatalf("utf8.RuneCountInString(%q) = %d, want %d", payload.Text, got, tt.wantRunes)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rejected requests must fail before anything is sent upstream: every case
|
||||||
|
// below returns on validation alone, so the test never reaches DeepL. The
|
||||||
|
// astral cases are the regression — 751 runes, which the old rune count
|
||||||
|
// accepted, but 1502 UTF-16 units, which oneshot answers with 400.
|
||||||
|
func TestTranslateByDLXRejectsOversizedTextsBeforeUpstream(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
texts []string
|
||||||
|
}{
|
||||||
|
{"one ASCII past the limit", []string{strings.Repeat("a", maxFreeTextLength+1)}},
|
||||||
|
{"astral characters past the limit", []string{strings.Repeat("😀", maxFreeTextLength/2+1)}},
|
||||||
|
{"combining marks past the limit", []string{strings.Repeat("e\u0301", maxFreeTextLength/2+1)}},
|
||||||
|
{"invalid UTF-8 past the limit", []string{strings.Repeat("\xf0\x90\x80", maxFreeTextLength/3+1)}},
|
||||||
|
// 800 runes in total, but two units each: a batch the rune count let
|
||||||
|
// through in a single request.
|
||||||
|
{"batch of astral characters past the limit", []string{strings.Repeat("😀", 400), strings.Repeat("😀", 400)}},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
_, length := textsToTranslate(tt.texts)
|
||||||
|
if length <= maxFreeTextLength {
|
||||||
|
t.Fatalf("textsToTranslate(%q) = %d, which is not over the limit", tt.texts, length)
|
||||||
|
}
|
||||||
|
result, err := TranslateByDLX("", "ZH", tt.texts, "", "", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("TranslateByDLX() error = %v", err)
|
||||||
|
}
|
||||||
|
if result.Code != http.StatusRequestEntityTooLarge {
|
||||||
|
t.Fatalf("TranslateByDLX() code = %d, want %d", result.Code, http.StatusRequestEntityTooLarge)
|
||||||
|
}
|
||||||
|
if want := fmt.Sprintf("%d", length); !strings.Contains(result.Message, want) {
|
||||||
|
t.Fatalf("TranslateByDLX() message = %q, want it to name %s", result.Message, want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
+116
-29
@@ -29,7 +29,6 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
"unicode/utf8"
|
|
||||||
|
|
||||||
"github.com/andybalholm/brotli"
|
"github.com/andybalholm/brotli"
|
||||||
"github.com/imroc/req/v3"
|
"github.com/imroc/req/v3"
|
||||||
@@ -99,8 +98,10 @@ const (
|
|||||||
|
|
||||||
// oneshot enforces a 1500-character hard cap on the total length of
|
// oneshot enforces a 1500-character hard cap on the total length of
|
||||||
// the `text` array for anonymous traffic (same limit the Chrome
|
// the `text` array for anonymous traffic (same limit the Chrome
|
||||||
// extension documents as G.notLoggedIn). Bail early to spare the
|
// extension documents as G.notLoggedIn). A character there is a UTF-16
|
||||||
// upstream and give the caller a faster error.
|
// code unit — what JavaScript's String.prototype.length and Kotlin's
|
||||||
|
// String.length report — so an astral character counts as two. Bail
|
||||||
|
// early to spare the upstream and give the caller a faster error.
|
||||||
maxFreeTextLength = 1500
|
maxFreeTextLength = 1500
|
||||||
|
|
||||||
// oneshotTimeout caps how long we wait on a single translate request.
|
// oneshotTimeout caps how long we wait on a single translate request.
|
||||||
@@ -416,17 +417,88 @@ func callOneshot(endpoint string, body []byte, bearerToken, proxyURL, appVersion
|
|||||||
return gjson.ParseBytes(raw), resp.StatusCode, nil
|
return gjson.ParseBytes(raw), resp.StatusCode, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// TranslateByDLX performs translation via the DeepL oneshot endpoint.
|
// textLength returns the length of text in UTF-16 code units — the unit
|
||||||
// Passing dlSession switches to the Pro endpoint; the value is sent
|
// oneshot's anonymous 1500-character cap counts, and the one the DeepL clients
|
||||||
// verbatim as the Bearer token (i.e. it must be an OAuth access token,
|
// this profile mirrors report (the iOS app is Kotlin, the extension is
|
||||||
// not the legacy dl_session cookie).
|
// JavaScript). An astral character is a surrogate pair and so counts as two,
|
||||||
func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, proxyURL string, dlSession string) (DLXTranslationResult, error) {
|
// where a rune count scores it one and lets an oversized request travel
|
||||||
if text == "" {
|
// upstream to be rejected there as a bare 400.
|
||||||
return DLXTranslationResult{
|
//
|
||||||
Code: http.StatusNotFound,
|
// Invalid UTF-8 needs no special case: the request body is decoded with
|
||||||
Message: "No text to translate",
|
// encoding/json before this runs, which replaces every invalid byte with
|
||||||
}, nil
|
// U+FFFD, and each replacement is one unit either way.
|
||||||
|
func textLength(text string) int {
|
||||||
|
n := 0
|
||||||
|
for _, r := range text {
|
||||||
|
if r > 0xFFFF {
|
||||||
|
n += 2
|
||||||
|
} else {
|
||||||
|
n++
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// textsToTranslate returns the positions of the texts that carry something to
|
||||||
|
// translate and their total length in UTF-16 code units. A blank text — empty,
|
||||||
|
// or nothing but whitespace — carries nothing to translate, so it is not sent:
|
||||||
|
// its own text is the answer, which keeps a segmented document position-aligned
|
||||||
|
// and lets an empty line pass through instead of failing the request.
|
||||||
|
func textsToTranslate(texts []string) (positions []int, total int) {
|
||||||
|
for i, text := range texts {
|
||||||
|
if strings.TrimSpace(text) == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
positions = append(positions, i)
|
||||||
|
total += textLength(text)
|
||||||
|
}
|
||||||
|
return positions, total
|
||||||
|
}
|
||||||
|
|
||||||
|
// mergeTranslations puts the translations back at the positions they were asked
|
||||||
|
// for, leaving every text that was not sent — a blank one — exactly as it
|
||||||
|
// arrived.
|
||||||
|
func mergeTranslations(texts []string, positions []int, translations []string) []string {
|
||||||
|
merged := make([]string, len(texts))
|
||||||
|
copy(merged, texts)
|
||||||
|
for i, position := range positions {
|
||||||
|
merged[position] = translations[i]
|
||||||
|
}
|
||||||
|
return merged
|
||||||
|
}
|
||||||
|
|
||||||
|
// translationsFromResult extracts exactly count non-empty translations from
|
||||||
|
// an oneshot response body. oneshot answers `text` arrays positionally, so a
|
||||||
|
// batch is all-or-nothing: if upstream returns a different number of
|
||||||
|
// translations or leaves one of them empty, the caller fails as a whole
|
||||||
|
// instead of answering with a misaligned list or a placeholder.
|
||||||
|
func translationsFromResult(result gjson.Result, count int) ([]string, error) {
|
||||||
|
translations := result.Get("translations").Array()
|
||||||
|
if len(translations) != count {
|
||||||
|
return nil, fmt.Errorf("expected %d translation(s), got %d", count, len(translations))
|
||||||
|
}
|
||||||
|
texts := make([]string, 0, count)
|
||||||
|
for _, translation := range translations {
|
||||||
|
text := translation.Get("text").String()
|
||||||
|
if text == "" {
|
||||||
|
return nil, errors.New("upstream returned an empty translation")
|
||||||
|
}
|
||||||
|
texts = append(texts, text)
|
||||||
|
}
|
||||||
|
return texts, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TranslateByDLX performs translation via the DeepL oneshot endpoint.
|
||||||
|
// texts holds one or more source strings: oneshot's `text` body field is an
|
||||||
|
// array, so a whole batch travels in a single upstream request and the
|
||||||
|
// returned Data stays position-aligned with texts. Passing dlSession switches
|
||||||
|
// to the Pro endpoint; the value is sent verbatim as the Bearer token (i.e.
|
||||||
|
// it must be an OAuth access token, not the legacy dl_session cookie).
|
||||||
|
func TranslateByDLX(sourceLang, targetLang string, texts []string, tagHandling string, proxyURL string, dlSession string) (DLXTranslationResult, error) {
|
||||||
|
// oneshot charges its anonymous cap against the total length of the
|
||||||
|
// `text` array, and a batch is one upstream request, so the cap applies
|
||||||
|
// to the sum of the texts that are actually sent.
|
||||||
|
positions, totalLength := textsToTranslate(texts)
|
||||||
|
|
||||||
resolvedTarget, err := resolveTargetLang(targetLang)
|
resolvedTarget, err := resolveTargetLang(targetLang)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -443,10 +515,26 @@ func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, pro
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if n := utf8.RuneCountInString(text); n > maxFreeTextLength {
|
if totalLength > maxFreeTextLength {
|
||||||
return DLXTranslationResult{
|
return DLXTranslationResult{
|
||||||
Code: http.StatusRequestEntityTooLarge,
|
Code: http.StatusRequestEntityTooLarge,
|
||||||
Message: fmt.Sprintf("text exceeds maximum length: %d characters (anonymous oneshot limit is %d)", n, maxFreeTextLength),
|
Message: fmt.Sprintf("text exceeds maximum length: %d characters (anonymous oneshot limit is %d)", totalLength, maxFreeTextLength),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nothing to translate: every text is blank, so none of them travels and
|
||||||
|
// the request is answered with its own texts — an empty list in, an empty
|
||||||
|
// list out — exactly as a blank element is inside a request that does have
|
||||||
|
// something to translate.
|
||||||
|
if len(positions) == 0 {
|
||||||
|
return DLXTranslationResult{
|
||||||
|
Code: http.StatusOK,
|
||||||
|
ID: time.Now().UnixMilli(),
|
||||||
|
Data: mergeTranslations(texts, positions, nil),
|
||||||
|
Alternatives: nil, // oneshot does not return alternatives
|
||||||
|
SourceLang: sourceLang,
|
||||||
|
TargetLang: targetLang,
|
||||||
|
Method: map[bool]string{true: "Pro", false: "Free"}[dlSession != ""],
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -459,8 +547,16 @@ func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, pro
|
|||||||
// app_information always agree; the lookup itself is cached (appversion.go).
|
// app_information always agree; the lookup itself is cached (appversion.go).
|
||||||
appVersion := currentIOSAppVersion()
|
appVersion := currentIOSAppVersion()
|
||||||
|
|
||||||
|
// Blank texts stay here: oneshot echoes an empty input, and the positional
|
||||||
|
// check on the answer would read that echo as a failed translation and fail
|
||||||
|
// the batch, so there is nothing to gain by sending them.
|
||||||
|
requested := make([]string, 0, len(positions))
|
||||||
|
for _, position := range positions {
|
||||||
|
requested = append(requested, texts[position])
|
||||||
|
}
|
||||||
|
|
||||||
reqStruct := oneshotRequest{
|
reqStruct := oneshotRequest{
|
||||||
Text: []string{text},
|
Text: requested,
|
||||||
TargetLang: resolvedTarget,
|
TargetLang: resolvedTarget,
|
||||||
SourceLang: resolvedSource, // empty = autodetect; omitempty drops the field
|
SourceLang: resolvedSource, // empty = autodetect; omitempty drops the field
|
||||||
// ItaClient.OneShotUsageType.translate (also: ocr, voiceforconversations)
|
// ItaClient.OneShotUsageType.translate (also: ocr, voiceforconversations)
|
||||||
@@ -532,8 +628,8 @@ func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, pro
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
translations := result.Get("translations").Array()
|
translations, err := translationsFromResult(result, len(requested))
|
||||||
if len(translations) == 0 {
|
if err != nil {
|
||||||
return DLXTranslationResult{
|
return DLXTranslationResult{
|
||||||
ID: id,
|
ID: id,
|
||||||
Code: http.StatusServiceUnavailable,
|
Code: http.StatusServiceUnavailable,
|
||||||
@@ -541,23 +637,14 @@ func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, pro
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
mainText := translations[0].Get("text").String()
|
if detected := result.Get("translations.0.detected_source_language").String(); detected != "" {
|
||||||
if mainText == "" {
|
|
||||||
return DLXTranslationResult{
|
|
||||||
ID: id,
|
|
||||||
Code: http.StatusServiceUnavailable,
|
|
||||||
Message: "Translation failed",
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if detected := translations[0].Get("detected_source_language").String(); detected != "" {
|
|
||||||
sourceLang = strings.ToUpper(detected)
|
sourceLang = strings.ToUpper(detected)
|
||||||
}
|
}
|
||||||
|
|
||||||
return DLXTranslationResult{
|
return DLXTranslationResult{
|
||||||
Code: http.StatusOK,
|
Code: http.StatusOK,
|
||||||
ID: id,
|
ID: id,
|
||||||
Data: mainText,
|
Data: mergeTranslations(texts, positions, translations),
|
||||||
Alternatives: nil, // oneshot does not return alternatives
|
Alternatives: nil, // oneshot does not return alternatives
|
||||||
SourceLang: sourceLang,
|
SourceLang: sourceLang,
|
||||||
TargetLang: targetLang,
|
TargetLang: targetLang,
|
||||||
|
|||||||
@@ -0,0 +1,180 @@
|
|||||||
|
package translate
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/tidwall/gjson"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTextsToTranslate(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
texts []string
|
||||||
|
wantAt []int
|
||||||
|
wantTotal int
|
||||||
|
}{
|
||||||
|
{"no texts", nil, nil, 0},
|
||||||
|
{"empty array", []string{}, nil, 0},
|
||||||
|
{"empty string", []string{""}, nil, 0},
|
||||||
|
{"every text empty", []string{"", ""}, nil, 0},
|
||||||
|
{"whitespace only", []string{" \t "}, nil, 0},
|
||||||
|
{"empty and blank", []string{"", " "}, nil, 0},
|
||||||
|
{"single text", []string{"Hello"}, []int{0}, 5},
|
||||||
|
{"empty element in batch", []string{"Hello", ""}, []int{0}, 5},
|
||||||
|
{"leading empty element in batch", []string{"", "Hello"}, []int{1}, 5},
|
||||||
|
{"blank elements around a batch", []string{"", "Hello", " ", "Good morning", "\n"}, []int{1, 3}, 17},
|
||||||
|
{"batch total", []string{"Hello", "Good morning"}, []int{0, 1}, 17},
|
||||||
|
{"counts UTF-16 units, not bytes", []string{"你好"}, []int{0}, 2},
|
||||||
|
{"astral character costs two units", []string{"😀"}, []int{0}, 2},
|
||||||
|
{"combining mark is two units, not one grapheme", []string{"e\u0301"}, []int{0}, 2},
|
||||||
|
{"invalid UTF-8 counts one unit per byte", []string{"\xf0\x90\x80"}, []int{0}, 3},
|
||||||
|
{"at the limit", []string{strings.Repeat("a", maxFreeTextLength)}, []int{0}, maxFreeTextLength},
|
||||||
|
{"astral at the limit", []string{strings.Repeat("😀", maxFreeTextLength/2)}, []int{0}, maxFreeTextLength},
|
||||||
|
{"astral past the limit", []string{strings.Repeat("😀", maxFreeTextLength/2), "😀"}, []int{0, 1}, maxFreeTextLength + 2},
|
||||||
|
{"astral batch sums units, not runes", []string{strings.Repeat("😀", 400), strings.Repeat("😀", 400)}, []int{0, 1}, 1600},
|
||||||
|
{"blank texts are not charged", []string{" ", "Hello"}, []int{1}, 5},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
at, total := textsToTranslate(tt.texts)
|
||||||
|
if total != tt.wantTotal || !reflect.DeepEqual(at, tt.wantAt) {
|
||||||
|
t.Fatalf("textsToTranslate(%q) = (%v, %d), want (%v, %d)", tt.texts, at, total, tt.wantAt, tt.wantTotal)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeTranslations(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
texts []string
|
||||||
|
positions []int
|
||||||
|
translations []string
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{"no blanks", []string{"Hello"}, []int{0}, []string{"你好"}, []string{"你好"}},
|
||||||
|
{"leading blank", []string{"", "Hello"}, []int{1}, []string{"你好"}, []string{"", "你好"}},
|
||||||
|
{"blank keeps its exact text", []string{"", "Hello", " "}, []int{1}, []string{"你好"}, []string{"", "你好", " "}},
|
||||||
|
{"batch keeps order", []string{"Hello", " ", "Good morning"}, []int{0, 2}, []string{"你好", "早上好"}, []string{"你好", " ", "早上好"}},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
if got := mergeTranslations(tt.texts, tt.positions, tt.translations); !reflect.DeepEqual(got, tt.want) {
|
||||||
|
t.Fatalf("mergeTranslations(%q, %v, %q) = %q, want %q", tt.texts, tt.positions, tt.translations, got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTranslationsFromResult(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
body string
|
||||||
|
count int
|
||||||
|
want []string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "single",
|
||||||
|
body: `{"translations":[{"text":"你好,世界!","detected_source_language":"en"}]}`,
|
||||||
|
count: 1,
|
||||||
|
want: []string{"你好,世界!"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "batch keeps order",
|
||||||
|
body: `{"translations":[{"text":"你好,世界!"},{"text":"早上好"}]}`,
|
||||||
|
count: 2,
|
||||||
|
want: []string{"你好,世界!", "早上好"},
|
||||||
|
},
|
||||||
|
{name: "no translations at all", body: `{}`, count: 1, wantErr: true},
|
||||||
|
{name: "fewer than requested", body: `{"translations":[{"text":"你好"}]}`, count: 2, wantErr: true},
|
||||||
|
{name: "more than requested", body: `{"translations":[{"text":"你好"},{"text":"早上好"}]}`, count: 1, wantErr: true},
|
||||||
|
{name: "empty translation", body: `{"translations":[{"text":"你好"},{"text":""}]}`, count: 2, wantErr: true},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got, err := translationsFromResult(gjson.Parse(tt.body), tt.count)
|
||||||
|
if (err != nil) != tt.wantErr {
|
||||||
|
t.Fatalf("translationsFromResult() error = %v, wantErr %v", err, tt.wantErr)
|
||||||
|
}
|
||||||
|
if tt.wantErr {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got, tt.want) {
|
||||||
|
t.Fatalf("translationsFromResult() = %q, want %q", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rejected requests must fail before anything is sent upstream: every case
|
||||||
|
// below returns on validation alone, so the test does not touch DeepL.
|
||||||
|
func TestTranslateByDLXValidationFailsBeforeUpstream(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
texts []string
|
||||||
|
code int
|
||||||
|
}{
|
||||||
|
{"over the limit", []string{strings.Repeat("a", maxFreeTextLength+1)}, http.StatusRequestEntityTooLarge},
|
||||||
|
{"batch over the limit", []string{strings.Repeat("a", maxFreeTextLength), "b"}, http.StatusRequestEntityTooLarge},
|
||||||
|
// 751 runes in the batch, but 1502 UTF-16 units: the case a rune count
|
||||||
|
// let through to be rejected by oneshot instead.
|
||||||
|
{"astral batch over the unit limit", []string{strings.Repeat("😀", maxFreeTextLength/2+1)}, http.StatusRequestEntityTooLarge},
|
||||||
|
{"astral batch split over the unit limit", []string{strings.Repeat("😀", 400), strings.Repeat("😀", 400)}, http.StatusRequestEntityTooLarge},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
result, err := TranslateByDLX("", "ZH", tt.texts, "", "", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("TranslateByDLX() error = %v", err)
|
||||||
|
}
|
||||||
|
if result.Code != tt.code {
|
||||||
|
t.Fatalf("TranslateByDLX() code = %d, want %d", result.Code, tt.code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every text is answered — translated when it carries something, returned as it
|
||||||
|
// is when it is blank — so nothing about emptiness is an error, and none of the
|
||||||
|
// cases below reaches DeepL. Data is always allocated, so an empty request
|
||||||
|
// marshals as `[]` rather than `null`.
|
||||||
|
func TestTranslateByDLXAnswersBlankTextsWithThemselves(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
texts []string
|
||||||
|
}{
|
||||||
|
{"no texts", nil},
|
||||||
|
{"empty array", []string{}},
|
||||||
|
{"single empty", []string{""}},
|
||||||
|
{"two empty", []string{"", ""}},
|
||||||
|
{"whitespace only", []string{" \t "}},
|
||||||
|
{"empty and whitespace", []string{"", " "}},
|
||||||
|
{"newlines and spaces", []string{"\n", "\t\n", " "}},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
result, err := TranslateByDLX("", "ZH", tt.texts, "", "", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("TranslateByDLX() error = %v", err)
|
||||||
|
}
|
||||||
|
if result.Code != http.StatusOK {
|
||||||
|
t.Fatalf("TranslateByDLX() code = %d, want %d", result.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
if result.Data == nil {
|
||||||
|
t.Fatal("TranslateByDLX() data = nil, want an allocated slice so it marshals as []")
|
||||||
|
}
|
||||||
|
if len(result.Data) != len(tt.texts) {
|
||||||
|
t.Fatalf("TranslateByDLX() data = %q, want %d element(s)", result.Data, len(tt.texts))
|
||||||
|
}
|
||||||
|
for i, text := range tt.texts {
|
||||||
|
if result.Data[i] != text {
|
||||||
|
t.Fatalf("TranslateByDLX() data[%d] = %q, want %q", i, result.Data[i], text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
+5
-1
@@ -16,11 +16,15 @@ package translate
|
|||||||
// handlers in the service package. The structure predates the migration to
|
// handlers in the service package. The structure predates the migration to
|
||||||
// the iOS oneshot endpoint; Alternatives is now always empty because oneshot
|
// the iOS oneshot endpoint; Alternatives is now always empty because oneshot
|
||||||
// does not return alternative translations, and ID is synthesized from time.
|
// does not return alternative translations, and ID is synthesized from time.
|
||||||
|
//
|
||||||
|
// Data holds one translation per requested text, in request order. The
|
||||||
|
// handlers render it as a bare string when the caller sent a bare string in
|
||||||
|
// `text` and as an array of the same length when the caller sent an array.
|
||||||
type DLXTranslationResult struct {
|
type DLXTranslationResult struct {
|
||||||
Code int `json:"code"`
|
Code int `json:"code"`
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
Message string `json:"message,omitempty"`
|
Message string `json:"message,omitempty"`
|
||||||
Data string `json:"data"`
|
Data []string `json:"data"`
|
||||||
Alternatives []string `json:"alternatives"`
|
Alternatives []string `json:"alternatives"`
|
||||||
SourceLang string `json:"source_lang"`
|
SourceLang string `json:"source_lang"`
|
||||||
TargetLang string `json:"target_lang"`
|
TargetLang string `json:"target_lang"`
|
||||||
|
|||||||
Reference in New Issue
Block a user