Compare commits

..
4 Commits
2 changed files with 107 additions and 36 deletions
+18 -3
View File
@@ -2,7 +2,7 @@
* @Author: Vincent Young * @Author: Vincent Young
* @Date: 2022-10-18 07:32:29 * @Date: 2022-10-18 07:32:29
* @LastEditors: Vincent Young * @LastEditors: Vincent Young
* @LastEditTime: 2023-11-28 00:24:20 * @LastEditTime: 2024-04-16 15:10:38
* @FilePath: /DeepLX/README.md * @FilePath: /DeepLX/README.md
* @Telegram: https://t.me/missuo * @Telegram: https://t.me/missuo
* *
@@ -69,9 +69,24 @@
- `-port` or `-p` : Listening port. Default is `1188`. - `-port` or `-p` : Listening port. Default is `1188`.
- `-token` : Access token. If you have set it up, each request needs to include `Authorization` in the **Headers** or `token` parameter in the **URL Params**. - `-token` : Access token. If you have set it up, each request needs to include `Authorization` in the **Headers** or `token` parameter in the **URL Params**.
- `-authkey` : DeepL Official `AuthKey`. If you have set it up, after the 429 response, the official AuthKey will be used for the request. If multiple authKeys are used simultaneously, they need to be separated by commas. - `-authkey` : DeepL Official `AuthKey`. If you have set it up, after the 429 response, the official AuthKey will be used for the request. If multiple authKeys are used simultaneously, they need to be separated by commas.
- `/v2/translate` : This endpoint is fully compatible with the DeepL official API. When using this endpoint, please strictly adhere to the request styles outlined in the official DeepL documentation. Note that in this endpoint, please use `DeepL-Auth-Key $token` in the `Authorization`, which is actually the Access Token, not the official `Auth Key` of DeepL.
#### Example of requesting a token-protected `/v2/translate` endpoint
```bash
curl -X POST 'http://localhost:1188/v2/translate' \
--header 'Authorization: DeepL-Auth-Key [yourAccessToken] [yourAuthKey]' \
--header 'Content-Type: application/json' \
--data '{
"text": [
"Hello, world!"
],
"target_lang": "DE"
}'
# Please note that either `yourAccessToken` or `yourAuthKey` can be omitted.
```
#### Requesting a token-protected **DeepLX API** instance using the `curl` #### Requesting a token-protected **DeepLX API** instance using the `curl`
``` ```bash
curl -X POST http://localhost:1188/translate \ curl -X POST http://localhost:1188/translate \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
-H "Authorization: Bearer your_access_token" \ -H "Authorization: Bearer your_access_token" \
@@ -82,7 +97,7 @@ curl -X POST http://localhost:1188/translate \
}' }'
``` ```
or or
``` ```bash
curl -X POST http://localhost:1188/translate?token=your_access_token \ curl -X POST http://localhost:1188/translate?token=your_access_token \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
-d '{ -d '{
+89 -33
View File
@@ -1,8 +1,8 @@
/* /*
* @Author: Vincent Yang * @Author: Vincent Yang
* @Date: 2023-07-01 21:45:34 * @Date: 2023-07-01 21:45:34
* @LastEditors: Vincent Yang * @LastEditors: Vincent Young
* @LastEditTime: 2024-03-20 16:39:58 * @LastEditTime: 2024-04-16 15:07:54
* @FilePath: /DeepLX/main.go * @FilePath: /DeepLX/main.go
* @Telegram: https://t.me/missuo * @Telegram: https://t.me/missuo
* @GitHub: https://github.com/missuo * @GitHub: https://github.com/missuo
@@ -314,16 +314,23 @@ func translateByDeepLX(sourceLang string, targetLang string, translateText strin
alternatives = append(alternatives, value.Get("text").String()) alternatives = append(alternatives, value.Get("text").String())
return true return true
}) })
return DeepLXTranslationResult{ if res.Get("result.texts.0.text").String() == "" {
Code: http.StatusOK, return DeepLXTranslationResult{
ID: id, Code: http.StatusServiceUnavailable,
Message: "Success", Message: "Translation failed, API returns an empty result.",
Data: res.Get("result.texts.0.text").String(), }, nil
Alternatives: alternatives, } else {
SourceLang: sourceLang, return DeepLXTranslationResult{
TargetLang: targetLang, Code: http.StatusOK,
Method: "Free", ID: id,
}, nil Message: "Success",
Data: res.Get("result.texts.0.text").String(),
Alternatives: alternatives,
SourceLang: sourceLang,
TargetLang: targetLang,
Method: "Free",
}, nil
}
} }
return DeepLXTranslationResult{ return DeepLXTranslationResult{
Code: http.StatusServiceUnavailable, Code: http.StatusServiceUnavailable,
@@ -331,6 +338,40 @@ func translateByDeepLX(sourceLang string, targetLang string, translateText strin
}, nil }, nil
} }
func authMiddleware(cfg *Config) gin.HandlerFunc {
return func(c *gin.Context) {
if cfg.Token != "" {
providedTokenInQuery := c.Query("token")
providedTokenInHeader := c.GetHeader("Authorization")
// Compatability with the Bearer token format
if providedTokenInHeader != "" {
parts := strings.Split(providedTokenInHeader, " ")
if len(parts) == 2 {
if parts[0] == "Bearer" || parts[0] == "DeepL-Auth-Key" {
providedTokenInHeader = parts[1]
} else {
providedTokenInHeader = ""
}
} else {
providedTokenInHeader = ""
}
}
if providedTokenInHeader != cfg.Token && providedTokenInQuery != cfg.Token {
c.JSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"message": "Invalid access token",
})
c.Abort()
return
}
}
c.Next()
}
}
func main() { func main() {
cfg := initConfig() cfg := initConfig()
@@ -358,22 +399,10 @@ func main() {
}) })
// Defining the translation endpoint which receives translation requests and returns translations // Defining the translation endpoint which receives translation requests and returns translations
r.POST("/translate", func(c *gin.Context) { r.POST("/translate", authMiddleware(cfg), func(c *gin.Context) {
req := PayloadFree{} req := PayloadFree{}
c.BindJSON(&req) c.BindJSON(&req)
if cfg.Token != "" {
providedTokenInQuery := c.Query("token")
providedTokenInHeader := c.GetHeader("Authorization")
if providedTokenInHeader != "Bearer "+cfg.Token && providedTokenInQuery != cfg.Token {
c.JSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"message": "Invalid access token",
})
return
}
}
sourceLang := req.SourceLang sourceLang := req.SourceLang
targetLang := req.TargetLang targetLang := req.TargetLang
translateText := req.TransText translateText := req.TransText
@@ -403,23 +432,50 @@ func main() {
} }
}) })
r.POST("/v2/translate", func(c *gin.Context) { r.POST("/v2/translate", authMiddleware(cfg), func(c *gin.Context) {
authorizationHeader := c.GetHeader("Authorization") authorizationHeader := c.GetHeader("Authorization")
parts := strings.Split(authorizationHeader, " ")
var authKey string var authKey string
if len(parts) == 2 {
authKey = parts[1] if strings.HasPrefix(authorizationHeader, "DeepL-Auth-Key") {
parts := strings.Split(authorizationHeader, " ")
if len(parts) >= 2 && strings.HasSuffix(parts[len(parts)-1], ":fx") {
authKey = parts[len(parts)-1]
}
} }
translateText := c.PostForm("text")
targetLang := c.PostForm("target_lang") var translateText string
var targetLang string
translateText = c.PostForm("text")
targetLang = c.PostForm("target_lang")
if translateText == "" || targetLang == "" {
var jsonData struct {
Text []string `json:"text"`
TargetLang string `json:"target_lang"`
}
if err := c.BindJSON(&jsonData); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"code": http.StatusBadRequest,
"message": "Invalid request payload",
})
return
}
translateText = strings.Join(jsonData.Text, "\n")
targetLang = jsonData.TargetLang
}
result, err := translateByDeepLX("", targetLang, translateText, authKey) result, err := translateByDeepLX("", targetLang, translateText, authKey)
if err != nil { if err != nil {
log.Fatalf("Translation failed: %s", err) log.Fatalf("Translation failed: %s", err)
} }
if result.Code == http.StatusOK { if result.Code == http.StatusOK {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"translations": []interface{}{ "translations": []map[string]interface{}{
map[string]interface{}{ {
"detected_source_language": result.SourceLang, "detected_source_language": result.SourceLang,
"text": result.Data, "text": result.Data,
}, },