diff --git a/README.md b/README.md index 84e4165..f929e98 100644 --- a/README.md +++ b/README.md @@ -63,12 +63,36 @@ Download the binary for your platform from [Releases](https://github.com/OwO-Net ### 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 +# Single text curl -X POST http://localhost:1188/translate \ -H "Content-Type: application/json" \ -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 Unicode characters (runes) 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 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. +- `"text": []`, and any array containing an empty string, are rejected with the same `404 {"code":404,"message":"No text to translate"}` as `"text": ""`. + ## Discussion Group [Telegram Group](https://t.me/+8KDGHKJCxEVkNzll) diff --git a/service/service.go b/service/service.go index b7d6aca..de0773a 100644 --- a/service/service.go +++ b/service/service.go @@ -13,6 +13,8 @@ package service import ( + "bytes" + "encoding/json" "fmt" "log" "net/http" @@ -74,6 +76,47 @@ type PayloadAPI struct { 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 decodes to the empty string exactly as it +// did when text was a plain string. +type PayloadText struct { + Texts []string + Batch bool +} + +// UnmarshalJSON implements json.Unmarshaler. +func (p *PayloadText) UnmarshalJSON(data []byte) error { + if trimmed := bytes.TrimSpace(data); 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 + } + + 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 { // Set Proxy proxyURL := os.Getenv("PROXY") @@ -107,7 +150,7 @@ func Router(cfg *Config) *gin.Engine { // Free API endpoint, No Pro Account required r.POST("/translate", authMiddleware(cfg), func(c *gin.Context) { - req := PayloadFree{} + req := PayloadTranslate{} if err := c.BindJSON(&req); err != nil { c.JSON(http.StatusBadRequest, gin.H{ "code": http.StatusBadRequest, @@ -118,7 +161,7 @@ func Router(cfg *Config) *gin.Engine { sourceLang := req.SourceLang targetLang := req.TargetLang - translateText := req.TransText + texts := req.Text.Texts tagHandling := req.TagHandling proxyURL := cfg.Proxy @@ -131,7 +174,7 @@ func Router(cfg *Config) *gin.Engine { return } - result, err := translate.TranslateByDLX(sourceLang, targetLang, translateText, tagHandling, proxyURL, "") + result, err := translate.TranslateByDLX(sourceLang, targetLang, texts, tagHandling, proxyURL, "") if err != nil { log.Printf("Translation failed: %s", err) c.JSON(http.StatusInternalServerError, gin.H{ @@ -142,15 +185,22 @@ func Router(cfg *Config) *gin.Engine { } if result.Code == http.StatusOK { - c.JSON(http.StatusOK, gin.H{ + response := gin.H{ "code": http.StatusOK, "id": result.ID, - "data": result.Data, "alternatives": result.Alternatives, "source_lang": result.SourceLang, "target_lang": result.TargetLang, "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 { c.JSON(result.Code, gin.H{ "code": result.Code, @@ -206,7 +256,7 @@ func Router(cfg *Config) *gin.Engine { 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 { log.Printf("Translation failed: %s", err) c.JSON(http.StatusInternalServerError, gin.H{ @@ -220,7 +270,7 @@ func Router(cfg *Config) *gin.Engine { c.JSON(http.StatusOK, gin.H{ "code": http.StatusOK, "id": result.ID, - "data": result.Data, + "data": result.Data[0], "alternatives": result.Alternatives, "source_lang": result.SourceLang, "target_lang": result.TargetLang, @@ -267,7 +317,7 @@ func Router(cfg *Config) *gin.Engine { targetLang = jsonData.TargetLang } - result, err := translate.TranslateByDLX(sourceLang, targetLang, translateText, "", proxyURL, "") + result, err := translate.TranslateByDLX(sourceLang, targetLang, []string{translateText}, "", proxyURL, "") if err != nil { log.Printf("Translation failed: %s", err) c.JSON(http.StatusInternalServerError, gin.H{ @@ -282,7 +332,7 @@ func Router(cfg *Config) *gin.Engine { "translations": []map[string]interface{}{ { "detected_source_language": result.SourceLang, - "text": result.Data, + "text": result.Data[0], }, }, }) diff --git a/service/service_test.go b/service/service_test.go new file mode 100644 index 0000000..ae108eb --- /dev/null +++ b/service/service_test.go @@ -0,0 +1,48 @@ +package service + +import ( + "encoding/json" + "reflect" + "strings" + "testing" +) + +// 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: []string{""}}, + {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) + } + }) + } +} diff --git a/translate/translate.go b/translate/translate.go index da50755..45f8033 100644 --- a/translate/translate.go +++ b/translate/translate.go @@ -416,12 +416,56 @@ func callOneshot(endpoint string, body []byte, bearerToken, proxyURL, appVersion return gjson.ParseBytes(raw), resp.StatusCode, nil } +// totalTextLength returns the total rune count of texts. ok is false when no +// text was requested or any of them is empty, which callers report as +// "No text to translate" — an empty element fails the batch as a whole rather +// than being skipped or translated as an empty segment. +func totalTextLength(texts []string) (total int, ok bool) { + if len(texts) == 0 { + return 0, false + } + for _, text := range texts { + if text == "" { + return 0, false + } + total += utf8.RuneCountInString(text) + } + return total, true +} + +// 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. -// 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, text string, tagHandling string, proxyURL string, dlSession string) (DLXTranslationResult, error) { - if text == "" { +// 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 requested texts rather than to each text. + totalLength, ok := totalTextLength(texts) + if !ok { return DLXTranslationResult{ Code: http.StatusNotFound, Message: "No text to translate", @@ -443,10 +487,10 @@ func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, pro }, nil } - if n := utf8.RuneCountInString(text); n > maxFreeTextLength { + if totalLength > maxFreeTextLength { return DLXTranslationResult{ 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 } @@ -460,7 +504,7 @@ func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, pro appVersion := currentIOSAppVersion() reqStruct := oneshotRequest{ - Text: []string{text}, + Text: texts, TargetLang: resolvedTarget, SourceLang: resolvedSource, // empty = autodetect; omitempty drops the field // ItaClient.OneShotUsageType.translate (also: ocr, voiceforconversations) @@ -532,8 +576,8 @@ func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, pro }, nil } - translations := result.Get("translations").Array() - if len(translations) == 0 { + data, err := translationsFromResult(result, len(texts)) + if err != nil { return DLXTranslationResult{ ID: id, Code: http.StatusServiceUnavailable, @@ -541,23 +585,14 @@ func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, pro }, nil } - mainText := translations[0].Get("text").String() - if mainText == "" { - return DLXTranslationResult{ - ID: id, - Code: http.StatusServiceUnavailable, - Message: "Translation failed", - }, nil - } - - if detected := translations[0].Get("detected_source_language").String(); detected != "" { + if detected := result.Get("translations.0.detected_source_language").String(); detected != "" { sourceLang = strings.ToUpper(detected) } return DLXTranslationResult{ Code: http.StatusOK, ID: id, - Data: mainText, + Data: data, Alternatives: nil, // oneshot does not return alternatives SourceLang: sourceLang, TargetLang: targetLang, diff --git a/translate/translate_test.go b/translate/translate_test.go new file mode 100644 index 0000000..cd4c87a --- /dev/null +++ b/translate/translate_test.go @@ -0,0 +1,104 @@ +package translate + +import ( + "net/http" + "reflect" + "strings" + "testing" + + "github.com/tidwall/gjson" +) + +func TestTotalTextLength(t *testing.T) { + tests := []struct { + name string + texts []string + wantTotal int + wantOK bool + }{ + {"no texts", nil, 0, false}, + {"empty array", []string{}, 0, false}, + {"empty string", []string{""}, 0, false}, + {"empty element in batch", []string{"Hello", ""}, 0, false}, + {"single text", []string{"Hello"}, 5, true}, + {"batch total", []string{"Hello", "Good morning"}, 17, true}, + {"counts runes, not bytes", []string{"你好"}, 2, true}, + {"at the limit", []string{strings.Repeat("a", maxFreeTextLength)}, maxFreeTextLength, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + total, ok := totalTextLength(tt.texts) + if ok != tt.wantOK || total != tt.wantTotal { + t.Fatalf("totalTextLength(%q) = (%d, %v), want (%d, %v)", tt.texts, total, ok, tt.wantTotal, tt.wantOK) + } + }) + } +} + +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 + }{ + {"no texts", nil, http.StatusNotFound}, + {"empty array", []string{}, http.StatusNotFound}, + {"empty element in batch", []string{"Hello", ""}, http.StatusNotFound}, + {"over the limit", []string{strings.Repeat("a", maxFreeTextLength+1)}, http.StatusRequestEntityTooLarge}, + {"batch over the limit", []string{strings.Repeat("a", maxFreeTextLength), "b"}, 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) + } + }) + } +} diff --git a/translate/types.go b/translate/types.go index db5d788..13bfa3a 100644 --- a/translate/types.go +++ b/translate/types.go @@ -16,11 +16,15 @@ package translate // handlers in the service package. The structure predates the migration to // the iOS oneshot endpoint; Alternatives is now always empty because oneshot // 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 { Code int `json:"code"` ID int64 `json:"id"` Message string `json:"message,omitempty"` - Data string `json:"data"` + Data []string `json:"data"` Alternatives []string `json:"alternatives"` SourceLang string `json:"source_lang"` TargetLang string `json:"target_lang"`