Compare commits

..
8 Commits
5 changed files with 126 additions and 235 deletions
+5 -207
View File
@@ -25,217 +25,15 @@
[6]: https://img.shields.io/docker/pulls/missuo/deeplx?logo=docker
[7]: https://img.shields.io/github/v/release/OwO-Network/DeepLX?logo=smartthings
## **Related Projects**
| Link | Description | Maintainer |
| ------------------------------------------------------------------- | ----------------------------------- | --------------------------------------------------------------- |
| [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 | [Vincent Yang](https://github.com/missuo) |
| [ifyour/deeplx](https://github.com/ifyour/deeplx) | JS Package for DeepLX (JavaScript) | [ifyour](https://github.com/ifyour) |
| [deeplx-serverless](https://github.com/LegendLeo/deeplx-serverless) | Serverless Package for DeepLX | [LegendLeo](https://github.com/LegendLeo/deeplx-serverless) |
## How to use
> \[!TIP]
>
> Learn more about [📘 Using DeepLX](https://deeplx.owo.network) by checking it out.
## Discussion Group
[Telegram Group](https://t.me/+8KDGHKJCxEVkNzll)
## Description
- `DeepLX` is listening to `0.0.0.0:1188` by default. You can modify the listening port by yourself.
- `DeepLX` is using `DeepL` Free API.
- `DeepLX` is unlimited to the number of requests.
## Usage
### For Developer
#### Request Parameters
- text: string
- source_lang: string
- target_lang: string
#### Response
```json
{
"alternatives": [
"Did you hear about this?",
"You've heard about this?",
"You've heard of this?"
],
"code": 200,
"data": "Have you heard about this?",
"id": 8356681003,
"method": "Free",
"source_lang": "ZH",
"target_lang": "EN"
}
```
### Custom Options
**The following settings are optional and not required.**
- `-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**.
- `-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.
- `-s`: `dl-session` is the cookie for a **DeepL Pro** account. If you set this, you will be able to use another endpoint `/v1/translate`, which can effectively avoid 429.
- `/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`
```bash
curl -X POST http://localhost:1188/translate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your_access_token" \
-d '{
"text": "Hello, world!",
"source_lang": "EN",
"target_lang": "DE"
}'
```
or
```bash
curl -X POST http://localhost:1188/translate?token=your_access_token \
-H "Content-Type: application/json" \
-d '{
"text": "Hello, world!",
"source_lang": "EN",
"target_lang": "DE"
}'
```
### Run with Docker
```bash
# ghcr.io
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" -e "DL_SESSION=xxxxx" ghcr.io/owo-network/deeplx:latest
# dockerhub
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" -e "DL_SESSION=xxxxx" missuo/deeplx:latest
```
### Run with Docker Compose
```bash
mkdir deeplx
cd deeplx
wget https://raw.githubusercontent.com/OwO-Network/DeepLX/main/compose.yaml
# modify environment variables
# environment:
# - TOKEN=helloxxx
# - AUTHKEY=xxxxxxx:fx
# - DL_SESSION=xxxxx
# docker compose
docker compose up -d
```
### Run on Linux Server
```bash
bash <(curl -Ls https://raw.githubusercontent.com/OwO-Network/DeepLX/main/install.sh)
# or
bash <(curl -Ls https://owo.nz/deeplx)
```
### Run on Mac
#### Homebrew (Recommended)
```bash
brew tap owo-network/brew
brew install deeplx
brew services start owo-network/brew/deeplx
# Update to the latest version
brew update
brew upgrade deeplx
brew services restart owo-network/brew/deeplx
# View the currently installed version
brew list --versions deeplx
```
#### Manual
1. Download the latest release of DeepL X.
```bash
sudo mv deeplx_darwin_amd64 /usr/local/bin/deeplx
sudo chmod +x /usr/local/bin/deeplx
```
2. Download the `me.missuo.deeplx.plist` to `~/Library/LaunchAgents`.
```bash
wget https://raw.githubusercontent.com/OwO-Network/DeepLX/main/me.missuo.deeplx.plist -O ~/Library/LaunchAgents/me.missuo.deeplx.plist
```
3. Run following command.
```bash
launchctl load ~/Library/LaunchAgents/me.missuo.deeplx.plist
launchctl start ~/Library/LaunchAgents/me.missuo.deeplx.plist
```
### Install from AUR
```bash
paru -S deeplx-bin
```
After installation, start the daemon with the following command.
```bash
systemctl daemon-reload
systemctl enable deeplx
```
**Special thanks to [AsukaMinato](https://github.com/asukaminato0721) for maintaining the updates of [ArchLinux packages](https://aur.archlinux.org/packages/deeplx-bin).**
### Run on Sealos
[![](https://raw.githubusercontent.com/labring-actions/templates/main/Deploy-on-Sealos.svg)](https://cloud.sealos.io/?openapp=system-template%3FtemplateName%3Ddeeplx)
## Setup on [Bob App](https://bobtranslate.com/)
1. Install [bob-plugin-deeplx](https://github.com/missuo/bob-plugin-deeplx) on Bob.
2. Setup the API. (If you use Brew to install locally you can skip this step)
![c5c19dd89df6fae1a256d](./img/c5c19dd89df6fae1a256d.png)
## Setup on [immersive-translate](https://github.com/immersive-translate/immersive-translate)
**It is not recommended, because the `immersive-translate` will send many requests in a short time, which will cause the `DeepL API` to block your IP.**
1. Install Latest [immersive-translate ](https://github.com/immersive-translate/immersive-translate/releases) on your browser.
2. Click on **Developer Settings** in the bottom left corner. **Enable Beta experimental features**.
3. Set the URL. (If you are not deploying locally, you need to change 127.0.0.1 to the IP of your server)
![6a48ba28621f2465028f0](./img/6a48ba28621f2465028f0.png)
## Use in Python
```python
import httpx, json
deeplx_api = "http://127.0.0.1:1188/translate"
data = {
"text": "Hello World",
"source_lang": "EN",
"target_lang": "ZH"
}
post_data = json.dumps(data)
r = httpx.post(url = deeplx_api, data = post_data).text
print(r)
```
## Backup the Docker Image of zu1k
```shell
docker run -itd -p 1188:80 missuo/deeplx-bk
```
**This docker image is not related to this project, as the original author deleted the image, it is only for backup.**
## Acknowledgements
### Contributors
+9 -1
View File
@@ -2,7 +2,7 @@
* @Author: Vincent Yang
* @Date: 2024-04-23 00:39:03
* @LastEditors: Vincent Yang
* @LastEditTime: 2024-04-23 00:43:43
* @LastEditTime: 2024-06-18 02:40:52
* @FilePath: /DeepLX/config.go
* @Telegram: https://t.me/missuo
* @GitHub: https://github.com/missuo
@@ -50,6 +50,14 @@ func initConfig() *Config {
}
}
// HTTP Proxy flag
flag.StringVar(&cfg.Proxy, "proxy", "", "set the proxy URL for HTTP requests")
if cfg.Proxy == "" {
if proxy, ok := os.LookupEnv("PROXY"); ok {
cfg.Proxy = proxy
}
}
flag.Parse()
return cfg
}
+29 -4
View File
@@ -2,7 +2,7 @@
* @Author: Vincent Yang
* @Date: 2023-07-01 21:45:34
* @LastEditors: Vincent Yang
* @LastEditTime: 2024-04-23 00:42:28
* @LastEditTime: 2024-06-18 02:41:55
* @FilePath: /DeepLX/main.go
* @Telegram: https://t.me/missuo
* @GitHub: https://github.com/missuo
@@ -15,6 +15,7 @@ import (
"fmt"
"log"
"net/http"
"net/url"
"os"
"strings"
@@ -62,6 +63,21 @@ func main() {
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>.")
// Set Proxy
proxyURL := os.Getenv("PROXY")
if proxyURL == "" {
proxyURL = cfg.Proxy
}
if proxyURL != "" {
proxy, err := url.Parse(proxyURL)
if err != nil {
log.Fatalf("Failed to parse proxy URL: %v", err)
}
http.DefaultTransport = &http.Transport{
Proxy: http.ProxyURL(proxy),
}
}
if cfg.Token != "" {
fmt.Println("Access token is set.")
}
@@ -91,8 +107,9 @@ func main() {
targetLang := req.TargetLang
translateText := req.TransText
authKey := cfg.AuthKey
proxyURL := cfg.Proxy
result, err := translateByDeepLX(sourceLang, targetLang, translateText, authKey)
result, err := translateByDeepLX(sourceLang, targetLang, translateText, authKey, proxyURL)
if err != nil {
log.Fatalf("Translation failed: %s", err)
}
@@ -124,8 +141,15 @@ func main() {
sourceLang := req.SourceLang
targetLang := req.TargetLang
translateText := req.TransText
proxyURL := cfg.Proxy
dlSession := cfg.DlSession
cookie := c.GetHeader("Cookie")
if cookie != "" {
dlSession = strings.Replace(cookie, "dl_session=", "", -1)
}
if dlSession == "" {
c.JSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
@@ -140,7 +164,7 @@ func main() {
return
}
result, err := translateByDeepLXPro(sourceLang, targetLang, translateText, dlSession)
result, err := translateByDeepLXPro(sourceLang, targetLang, translateText, dlSession, proxyURL)
if err != nil {
log.Fatalf("Translation failed: %s", err)
}
@@ -168,6 +192,7 @@ func main() {
r.POST("/v2/translate", authMiddleware(cfg), func(c *gin.Context) {
authorizationHeader := c.GetHeader("Authorization")
var authKey string
proxyURL := cfg.Proxy
if strings.HasPrefix(authorizationHeader, "DeepL-Auth-Key") {
parts := strings.Split(authorizationHeader, " ")
@@ -200,7 +225,7 @@ func main() {
targetLang = jsonData.TargetLang
}
result, err := translateByDeepLX("", targetLang, translateText, authKey)
result, err := translateByDeepLX("", targetLang, translateText, authKey, proxyURL)
if err != nil {
log.Fatalf("Translation failed: %s", err)
}
+78 -19
View File
@@ -6,6 +6,7 @@ import (
"io"
"log"
"net/http"
"net/url"
"strings"
"github.com/abadojack/whatlanggo"
@@ -14,6 +15,24 @@ import (
)
func initDeepLXData(sourceLang string, targetLang string) *PostData {
hasRegionalVariant := false
targetLangParts := strings.Split(targetLang, "-")
// targetLang can be "en", "pt", "pt-PT", "pt-BR"
// targetLangCode is the first part of the targetLang, e.g. "pt" in "pt-PT"
targetLangCode := targetLangParts[0]
if len(targetLangParts) > 1 {
hasRegionalVariant = true
}
commonJobParams := CommonJobParams{
WasSpoken: false,
TranscribeAS: "",
}
if hasRegionalVariant {
commonJobParams.RegionalVariant = targetLang
}
return &PostData{
Jsonrpc: "2.0",
Method: "LMT_handle_texts",
@@ -21,19 +40,15 @@ func initDeepLXData(sourceLang string, targetLang string) *PostData {
Splitting: "newlines",
Lang: Lang{
SourceLangUserSelected: sourceLang,
TargetLang: targetLang,
},
CommonJobParams: CommonJobParams{
WasSpoken: false,
TranscribeAS: "",
// RegionalVariant: "en-US",
TargetLang: targetLangCode,
},
CommonJobParams: commonJobParams,
},
}
}
func translateByOfficialAPI(text string, sourceLang string, targetLang string, authKey string) (string, error) {
url := "https://api-free.deepl.com/v2/translate"
func translateByOfficialAPI(text string, sourceLang string, targetLang string, authKey string, proxyURL string) (string, error) {
freeURL := "https://api-free.deepl.com/v2/translate"
textArray := strings.Split(text, "\n")
payload := PayloadAPI{
@@ -47,7 +62,7 @@ func translateByOfficialAPI(text string, sourceLang string, targetLang string, a
return "", err
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes))
req, err := http.NewRequest("POST", freeURL, bytes.NewBuffer(payloadBytes))
if err != nil {
return "", err
}
@@ -55,7 +70,20 @@ func translateByOfficialAPI(text string, sourceLang string, targetLang string, a
req.Header.Set("Authorization", "DeepL-Auth-Key "+authKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
var client *http.Client
if proxyURL != "" {
proxy, err := url.Parse(proxyURL)
if err != nil {
return "", err
}
transport := &http.Transport{
Proxy: http.ProxyURL(proxy),
}
client = &http.Client{Transport: transport}
} else {
client = &http.Client{}
}
resp, err := client.Do(req)
if err != nil {
return "", err
@@ -83,7 +111,7 @@ func translateByOfficialAPI(text string, sourceLang string, targetLang string, a
return sb.String(), nil
}
func translateByDeepLX(sourceLang string, targetLang string, translateText string, authKey string) (DeepLXTranslationResult, error) {
func translateByDeepLX(sourceLang string, targetLang string, translateText string, authKey string, proxyURL string) (DeepLXTranslationResult, error) {
id := getRandomNumber()
if sourceLang == "" {
lang := whatlanggo.DetectLang(translateText)
@@ -103,7 +131,7 @@ func translateByDeepLX(sourceLang string, targetLang string, translateText strin
}
// Preparing the request data for the DeepL API
url := "https://www2.deepl.com/jsonrpc"
www2URL := "https://www2.deepl.com/jsonrpc"
id = id + 1
postData := initDeepLXData(sourceLang, targetLang)
text := Text{
@@ -128,7 +156,7 @@ func translateByDeepLX(sourceLang string, targetLang string, translateText strin
// Creating a new HTTP POST request with the JSON data as the body
post_byte = []byte(postStr)
reader := bytes.NewReader(post_byte)
request, err := http.NewRequest("POST", url, reader)
request, err := http.NewRequest("POST", www2URL, reader)
if err != nil {
log.Println(err)
@@ -152,7 +180,23 @@ func translateByDeepLX(sourceLang string, targetLang string, translateText strin
request.Header.Set("Connection", "keep-alive")
// Making the HTTP request to the DeepL API
client := &http.Client{}
var client *http.Client
if proxyURL != "" {
proxy, err := url.Parse(proxyURL)
if err != nil {
return DeepLXTranslationResult{
Code: http.StatusServiceUnavailable,
Message: "Uknown error",
}, nil
}
transport := &http.Transport{
Proxy: http.ProxyURL(proxy),
}
client = &http.Client{Transport: transport}
} else {
client = &http.Client{}
}
resp, err := client.Do(request)
if err != nil {
log.Println(err)
@@ -194,7 +238,7 @@ func translateByDeepLX(sourceLang string, targetLang string, translateText strin
continue
} else {
if validity {
translatedText, err := translateByOfficialAPI(translateText, sourceLang, targetLang, authKey)
translatedText, err := translateByOfficialAPI(translateText, sourceLang, targetLang, authKey, proxyURL)
if err != nil {
return DeepLXTranslationResult{
Code: http.StatusTooManyRequests,
@@ -244,7 +288,7 @@ func translateByDeepLX(sourceLang string, targetLang string, translateText strin
}, nil
}
func translateByDeepLXPro(sourceLang string, targetLang string, translateText string, dlSession string) (DeepLXTranslationResult, error) {
func translateByDeepLXPro(sourceLang string, targetLang string, translateText string, dlSession string, proxyURL string) (DeepLXTranslationResult, error) {
id := getRandomNumber()
if sourceLang == "" {
lang := whatlanggo.DetectLang(translateText)
@@ -264,7 +308,7 @@ func translateByDeepLXPro(sourceLang string, targetLang string, translateText st
}
// Preparing the request data for the DeepL API
url := "https://api.deepl.com/jsonrpc"
proURL := "https://api.deepl.com/jsonrpc"
id = id + 1
postData := initDeepLXData(sourceLang, targetLang)
text := Text{
@@ -289,7 +333,7 @@ func translateByDeepLXPro(sourceLang string, targetLang string, translateText st
// Creating a new HTTP POST request with the JSON data as the body
post_byte = []byte(postStr)
reader := bytes.NewReader(post_byte)
request, err := http.NewRequest("POST", url, reader)
request, err := http.NewRequest("POST", proURL, reader)
if err != nil {
log.Println(err)
@@ -310,7 +354,22 @@ func translateByDeepLXPro(sourceLang string, targetLang string, translateText st
request.Header.Set("Cookie", "dl_session="+dlSession)
// Making the HTTP request to the DeepL API
client := &http.Client{}
var client *http.Client
if proxyURL != "" {
proxy, err := url.Parse(proxyURL)
if err != nil {
return DeepLXTranslationResult{
Code: http.StatusServiceUnavailable,
Message: "DeepL API request failed",
}, nil
}
transport := &http.Transport{
Proxy: http.ProxyURL(proxy),
}
client = &http.Client{Transport: transport}
} else {
client = &http.Client{}
}
resp, err := client.Do(request)
if err != nil {
log.Println(err)
+5 -4
View File
@@ -2,7 +2,7 @@
* @Author: Vincent Yang
* @Date: 2024-03-20 15:43:57
* @LastEditors: Vincent Yang
* @LastEditTime: 2024-04-23 00:37:39
* @LastEditTime: 2024-06-18 02:38:48
* @FilePath: /DeepLX/types.go
* @Telegram: https://t.me/missuo
* @GitHub: https://github.com/missuo
@@ -16,6 +16,7 @@ type Config struct {
Token string
AuthKey string
DlSession string
Proxy string
}
type Lang struct {
@@ -24,9 +25,9 @@ type Lang struct {
}
type CommonJobParams struct {
WasSpoken bool `json:"wasSpoken"`
TranscribeAS string `json:"transcribe_as"`
// RegionalVariant string `json:"regionalVariant"`
WasSpoken bool `json:"wasSpoken"`
TranscribeAS string `json:"transcribe_as"`
RegionalVariant string `json:"regionalVariant,omitempty"`
}
type Params struct {