Compare commits

..
8 Commits
Author SHA1 Message Date
Vincent Young 9ca3249919 fix: known bug 2023-11-28 21:02:21 -05:00
Vincent Young 9b2d712469 feat: support multiple authkeys 2023-11-28 00:24:41 -05:00
Vincent Young 5e080f3871 fix: remove unnecessary variables 2023-11-27 15:10:39 -05:00
Vincent Young d93ac81ea2 docs: fix related projects 2023-11-27 15:08:16 -05:00
Vincent Young fdcac338fe docs: fix 2023-11-27 15:04:46 -05:00
Vincent Young 5489e11113 refactor: unified parameter 2023-11-27 14:50:32 -05:00
Vincent Young 365cf185a4 chore: fix 2023-11-27 14:06:45 -05:00
Vincent Young 6710536837 chore: fix compose demo 2023-11-27 14:01:24 -05:00
3 changed files with 142 additions and 100 deletions
+31 -28
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-19 19:21:24 * @LastEditTime: 2023-11-28 00:24:20
* @FilePath: /DeepLX/README.md * @FilePath: /DeepLX/README.md
* @Telegram: https://t.me/missuo * @Telegram: https://t.me/missuo
* *
@@ -28,9 +28,9 @@
## **Related Projects** ## **Related Projects**
| Link | Description | Maintainer | | Link | Description | Maintainer |
| ------------------------------------------ | -------------------------------------- | ----------------- | | ------------------------------------------ | -------------------------------------- | ----------------- |
| [OwO-Network/PyDeepLX](https://github.com/OwO-Network/PyDeepLX) | Python Package for DeepLX | OwO-Network | | [OwO-Network/PyDeepLX](https://github.com/OwO-Network/PyDeepLX) | Python Package for DeepLX | [Vincent Yang](https://github.com/missuo) |
| [OwO-Network/gdeeplx](https://github.com/OwO-Network/gdeeplx) | Golang Package for DeepLX | OwO-Network | | [OwO-Network/gdeeplx](https://github.com/OwO-Network/gdeeplx) | Golang Package for DeepLX | [Vincent Yang](https://github.com/missuo) |
| [ifyour/deeplx](https://github.com/ifyour/deeplx) | JS Package for DeepLX (JavaScript) | ifyour | | [ifyour/deeplx](https://github.com/ifyour/deeplx) | JS Package for DeepLX (JavaScript) | [ifyour](https://github.com/ifyour) |
## Discussion Group ## Discussion Group
[Telegram Group](https://t.me/+8KDGHKJCxEVkNzll) [Telegram Group](https://t.me/+8KDGHKJCxEVkNzll)
@@ -41,39 +41,35 @@
- `DeepLX` is unlimited to the number of requests. - `DeepLX` is unlimited to the number of requests.
## Usage ## Usage
### Request Parameters ### For Developer
#### Request Parameters
- text: string - text: string
- source_lang: string - source_lang: string
- target_lang: string - target_lang: string
### Response #### Response
```json ```json
{ {
"alternatives": [ "alternatives": [
"no one else", "Did you hear about this?",
"there is no other person (idiom); there is no one else", "You've heard about this?",
"there is no other person" "You've heard of this?"
], ],
"code": 200, "code": 200,
"data": "there is no one else", "data": "Have you heard about this?",
"id": 8352115005, "id": 8356681003,
"method": "Free",
"source_lang": "ZH", "source_lang": "ZH",
"target_lang": "EN" "target_lang": "EN"
} }
``` ```
### Specify the port (Optional) ### Custom Options
**Thanks to [cijiugechu](https://github.com/cijiugechu) for [his contribution](https://github.com/OwO-Network/DeepLX/commit/4a0920579ea868b0f05ccdff6bceae316bfd5dc8) to make this feature possible for this project!** **The following settings are optional and not required.**
```bash - `-port` or `-p` : Listening port. Default is `1188`.
./deeplx -p 3333 - `-token` : Access token. If you have set it up, each request will need to include an `Authorization` header.
# or - `-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.
./deeplx -port 3333
```
### Set access password (Optional)
**To prevent abuse of your public API, you can use a token to restrict translation requests.**
```bash
./deeplx -token hellodeeplx
```
#### Requesting a token-protected **DeepLX API** instance using the `curl`
``` ```
curl -X POST http://localhost:1188/translate \ curl -X POST http://localhost:1188/translate \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
@@ -83,7 +79,6 @@ curl -X POST http://localhost:1188/translate \
"source_lang": "EN", "source_lang": "EN",
"target_lang": "DE" "target_lang": "DE"
}' }'
``` ```
### Run with Docker ### Run with Docker
@@ -91,18 +86,26 @@ curl -X POST http://localhost:1188/translate \
# ghcr.io # ghcr.io
docker run -itd -p 1188:1188 ghcr.io/owo-network/deeplx:latest docker run -itd -p 1188:1188 ghcr.io/owo-network/deeplx:latest
# custom environment variables
docker run -itd -p 1188:1188 -e "TOKEN=helloxxx" -e "AUTHKEY=xxxx:fx" ghcr.io/owo-network/deeplx:latest
# dockerhub # dockerhub
docker run -itd -p 1188:1188 missuo/deeplx:latest docker run -itd -p 1188:1188 missuo/deeplx:latest
# custom environment variables
docker run -itd -p 1188:1188 -e "TOKEN=helloxxx" -e "AUTHKEY=xxxx:fx" missuo/deeplx:latest
``` ```
### Run with Docker Compose ### Run with Docker Compose
```bash ```bash
mkdir deeplx mkdir deeplx
cd deeplx cd deeplx
wget https://raw.githubusercontent.com/OwO-Network/DeepLX/main/docker-compose.yaml wget https://raw.githubusercontent.com/OwO-Network/DeepLX/main/compose.yaml
# docker compose v1 # modify environment variables
docker-compose up -d # environment:
# or docker compose v2 # - TOKEN=helloxxx
# - AUTHKEY=xxxxxxx:fx
# docker compose
docker compose up -d docker compose up -d
``` ```
+3
View File
@@ -6,3 +6,6 @@ services:
restart: always restart: always
ports: ports:
- "1188:1188" - "1188:1188"
# environment:
# - TOKEN=helloworld
# - AUTHKEY=xxxxxxx:fx
+107 -71
View File
@@ -2,7 +2,7 @@
* @Author: Vincent Young * @Author: Vincent Young
* @Date: 2023-07-01 21:45:34 * @Date: 2023-07-01 21:45:34
* @LastEditors: Vincent Young * @LastEditors: Vincent Young
* @LastEditTime: 2023-11-27 11:59:51 * @LastEditTime: 2023-11-28 21:02:08
* @FilePath: /DeepLX/main.go * @FilePath: /DeepLX/main.go
* @Telegram: https://t.me/missuo * @Telegram: https://t.me/missuo
* *
@@ -32,21 +32,36 @@ import (
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
) )
var port int type Config struct {
var token string Port int
var authKey string Token string
AuthKey string
}
func init() { func InitConfig() *Config {
const ( cfg := &Config{
defaultPort = 1188 Port: 1188,
usage = "set up the port to listen on" }
)
flag.IntVar(&port, "port", defaultPort, usage) flag.IntVar(&cfg.Port, "port", cfg.Port, "set up the port to listen on")
flag.IntVar(&port, "p", defaultPort, usage) flag.IntVar(&cfg.Port, "p", cfg.Port, "set up the port to listen on")
flag.StringVar(&token, "token", "", "set the access token for /translate endpoint")
log.SetFlags(log.LstdFlags | log.Lshortfile) flag.StringVar(&cfg.Token, "token", "", "set the access token for /translate endpoint")
if cfg.Token == "" {
if token, ok := os.LookupEnv("TOKEN"); ok {
cfg.Token = token
}
}
flag.StringVar(&cfg.AuthKey, "authkey", "", "The authentication key for DeepL API")
if cfg.AuthKey == "" {
if authKey, ok := os.LookupEnv("AUTHKEY"); ok {
cfg.AuthKey = authKey
}
}
flag.Parse()
return cfg
} }
type Lang struct { type Lang struct {
@@ -119,17 +134,16 @@ func getTimeStamp(iCount int64) int64 {
} }
} }
type ResData struct { type PayloadFree struct {
TransText string `json:"text"` TransText string `json:"text"`
SourceLang string `json:"source_lang"` SourceLang string `json:"source_lang"`
TargetLang string `json:"target_lang"` TargetLang string `json:"target_lang"`
} }
type Payload struct { type PayloadAPI struct {
Text []string `json:"text"` Text []string `json:"text"`
TargetLang string `json:"target_lang"` TargetLang string `json:"target_lang"`
SourceLang string `json:"source_lang"` SourceLang string `json:"source_lang"`
GlossaryID string `json:"glossary_id"`
} }
type Translation struct { type Translation struct {
@@ -140,11 +154,11 @@ type TranslationResponse struct {
Translations []Translation `json:"translations"` Translations []Translation `json:"translations"`
} }
func translateByAPI(text string, targetLang string, sourceLang string, authKey string) (string, error) { func translateByAPI(text string, sourceLang string, targetLang string, authKey string) (string, error) {
url := "https://api-free.deepl.com/v2/translate" url := "https://api-free.deepl.com/v2/translate"
textArray := strings.Split(text, "\n") textArray := strings.Split(text, "\n")
payload := Payload{ payload := PayloadAPI{
Text: textArray, Text: textArray,
TargetLang: targetLang, TargetLang: targetLang,
SourceLang: sourceLang, SourceLang: sourceLang,
@@ -191,40 +205,51 @@ func translateByAPI(text string, targetLang string, sourceLang string, authKey s
return sb.String(), nil return sb.String(), nil
} }
func main() { type DeepLResponse struct {
// Parsing the command-line flags CharacterCount int `json:"character_count"`
flag.StringVar(&authKey, "authkey", "", "The authentication key for DeepL API") CharacterLimit int `json:"character_limit"`
flag.Parse() }
// Displaying initialization information func checkUsage(authKey string) (bool, error) {
fmt.Printf("DeepL X has been successfully launched! Listening on 0.0.0.0:%v\n", port) url := "https://api-free.deepl.com/v2/usage"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return false, err
}
req.Header.Add("Authorization", "DeepL-Auth-Key "+authKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return false, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return false, err
}
var response DeepLResponse
err = json.Unmarshal(body, &response)
if err != nil {
return false, err
}
return response.CharacterCount < 499900, nil
}
func main() {
cfg := InitConfig()
fmt.Printf("DeepL X has been successfully launched! Listening on 0.0.0.0:%v\n", cfg.Port)
fmt.Println("Developed by sjlleo <i@leo.moe> and missuo <me@missuo.me>.") fmt.Println("Developed by sjlleo <i@leo.moe> and missuo <me@missuo.me>.")
// Check if the token is set in the environment variable if cfg.Token != "" {
if token == "" { fmt.Println("Access token is set.")
envToken, ok := os.LookupEnv("TOKEN")
if ok {
token = envToken
fmt.Println("Access token is set from the environment variable.")
}
} }
if cfg.AuthKey != "" {
if token == "" { fmt.Println("DeepL Official Authentication key is set.")
fmt.Println("Access token is not set. You can set it using the -token flag or the TOKEN environment variable.")
} else {
fmt.Println("Access token is set. Use the Authorization: Bearer <token> header to access /translate.")
}
if authKey == "" {
envAuthKey, ok := os.LookupEnv("AUTHKEY")
if ok {
authKey = envAuthKey
fmt.Println("Authentication key is set from the environment variable.")
} else {
fmt.Println("Authentication key is not set. You can set it using the -authkey flag or the AUTHKEY environment variable.")
}
} else {
fmt.Println("Authentication key is set via command-line.")
} }
// Generating a random ID // Generating a random ID
@@ -245,12 +270,12 @@ 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", func(c *gin.Context) {
reqj := ResData{} req := PayloadFree{}
c.BindJSON(&reqj) c.BindJSON(&req)
if token != "" { if cfg.Token != "" {
providedToken := c.GetHeader("Authorization") providedToken := c.GetHeader("Authorization")
if providedToken != "Bearer "+token { if providedToken != "Bearer "+cfg.Token {
c.JSON(http.StatusUnauthorized, gin.H{ c.JSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized, "code": http.StatusUnauthorized,
"message": "Invalid access token", "message": "Invalid access token",
@@ -260,9 +285,9 @@ func main() {
} }
// Extracting details from the request JSON // Extracting details from the request JSON
sourceLang := reqj.SourceLang sourceLang := req.SourceLang
targetLang := reqj.TargetLang targetLang := req.TargetLang
translateText := reqj.TransText translateText := req.TransText
// If source language is not specified, auto-detect it // If source language is not specified, auto-detect it
if sourceLang == "" { if sourceLang == "" {
@@ -361,21 +386,33 @@ func main() {
} }
if resp.StatusCode == http.StatusTooManyRequests { if resp.StatusCode == http.StatusTooManyRequests {
translatedText, err := translateByAPI(translateText, sourceLang, targetLang, authKey) authKeyArray := strings.Split(cfg.AuthKey, ",")
if err != nil { for _, authKey := range authKeyArray {
c.JSON(http.StatusTooManyRequests, gin.H{ validity, err := checkUsage(authKey)
"code": http.StatusTooManyRequests, if err != nil {
"message": "Too Many Requests", continue
}) } else {
if validity == true {
translatedText, err := translateByAPI(translateText, sourceLang, targetLang, authKey)
if err != nil {
c.JSON(http.StatusTooManyRequests, gin.H{
"code": http.StatusTooManyRequests,
"message": "Too Many Requests",
})
}
c.JSON(http.StatusOK, gin.H{
"code": http.StatusOK,
"id": 1000000,
"data": translatedText,
"source_lang": sourceLang,
"target_lang": targetLang,
"method": "Official API",
})
return
}
}
} }
c.JSON(http.StatusOK, gin.H{
"code": http.StatusOK,
"id": 1000000,
"data": translatedText,
"source_lang": sourceLang,
"target_lang": targetLang,
"method": "Official API",
})
} else { } else {
var alternatives []string var alternatives []string
res.Get("result.texts.0.alternatives").ForEach(func(key, value gjson.Result) bool { res.Get("result.texts.0.alternatives").ForEach(func(key, value gjson.Result) bool {
@@ -402,11 +439,10 @@ func main() {
}) })
}) })
// Determining which port to run the server on, with a fallback to a default port
envPort, ok := os.LookupEnv("PORT") envPort, ok := os.LookupEnv("PORT")
if ok { if ok {
r.Run(":" + envPort) r.Run(":" + envPort)
} else { } else {
r.Run(fmt.Sprintf(":%v", port)) r.Run(fmt.Sprintf(":%v", cfg.Port))
} }
} }