Compare commits

...
12 Commits
3 changed files with 142 additions and 104 deletions
+1 -1
View File
@@ -1 +1 @@
deepl-api DeepLX
+9 -7
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-05-30 01:29:33 * @LastEditTime: 2023-07-23 20:42:10
* @FilePath: /DeepLX/README.md * @FilePath: /DeepLX/README.md
* @Telegram: https://t.me/missuo * @Telegram: https://t.me/missuo
* *
@@ -13,9 +13,6 @@
</h1> </h1>
<h4 align="center">Permanently free DeepL API written in Golang.</h4> <h4 align="center">Permanently free DeepL API written in Golang.</h4>
<p align="center"> <p align="center">
<a href="https://github.com/OwO-Network/DeepLX/actions">
<img src="https://img.shields.io/github/actions/workflow/status/OwO-Network/DeepLX/build.yml?branch=main&style=flat-square" alt="Github Actions">
</a>
<a href="https://goreportcard.com/report/github.com/OwO-Network/DeepLX"> <a href="https://goreportcard.com/report/github.com/OwO-Network/DeepLX">
<img src="https://goreportcard.com/badge/github.com/OwO-Network/DeepLX?style=flat-square"> <img src="https://goreportcard.com/badge/github.com/OwO-Network/DeepLX?style=flat-square">
</a> </a>
@@ -24,8 +21,13 @@
</a> </a>
</p> </p>
## **Python Package** ## **Related Projects**
[OwO-Network/PyDeepLX](https://github.com/OwO-Network/PyDeepLX) [OwO-Network/PyDeepLX](https://github.com/OwO-Network/PyDeepLX): Python Package for DeepLX.
[OwO-Network/gdeeplx](https://github.com/OwO-Network/gdeeplx): Golang Package for DeepLX.
## Discussion Group
[Telegram Group](https://t.me/+8KDGHKJCxEVkNzll)
## Description ## Description
- `DeepLX` is listening to `0.0.0.0:1188` by default. You can modify the listening port by yourself. - `DeepLX` is listening to `0.0.0.0:1188` by default. You can modify the listening port by yourself.
@@ -88,7 +90,7 @@ bash <(curl -Ls https://cpp.li/deeplx)
### Run on Mac ### Run on Mac
#### Homebrew (Recommended) #### Homebrew (Recommended)
**For unknown reasons v0.7.8 does not work properly with Homebrew, so we are still using v0.7.7 for our version of Homebrew, it has no bugs and it is almost perfect.** **Homebrew has been fixed in the latest version and works perfectly.**
```bash ```bash
brew tap owo-network/brew brew tap owo-network/brew
brew install deeplx brew install deeplx
+54 -18
View File
@@ -1,3 +1,14 @@
/*
* @Author: Vincent Young
* @Date: 2023-07-01 21:45:34
* @LastEditors: Vincent Young
* @LastEditTime: 2023-09-14 13:34:42
* @FilePath: /DeepLX/main.go
* @Telegram: https://t.me/missuo
*
* Copyright © 2023 by Vincent, All Rights Reserved.
*/
package main package main
import ( import (
@@ -9,6 +20,7 @@ import (
"log" "log"
"math/rand" "math/rand"
"net/http" "net/http"
"os"
"strings" "strings"
"time" "time"
@@ -110,50 +122,58 @@ type ResData struct {
} }
func main() { func main() {
// parse flags // Parsing the command-line flags
flag.Parse() flag.Parse()
// display information // Displaying initialization information
fmt.Printf("DeepL X has been successfully launched! Listening on 0.0.0.0:%v\n", port) fmt.Printf("DeepL X has been successfully launched! Listening on 0.0.0.0:%v\n", port)
fmt.Println("Made by sjlleo and missuo.") fmt.Println("Developed by sjlleo <i@leo.moe> and missuo <me@missuo.me>.")
// create a random id // Generating a random ID
id := getRandomNumber() id := getRandomNumber()
// set release mode // Setting the application to release mode
gin.SetMode(gin.ReleaseMode) gin.SetMode(gin.ReleaseMode)
r := gin.Default() r := gin.Default()
r.Use(cors.Default()) r.Use(cors.Default())
// Defining the root endpoint which returns the project details
r.GET("/", func(c *gin.Context) { r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"code": 200, "code": 200,
"message": "DeepL Free API, Made by sjlleo and missuo. Go to /translate with POST. http://github.com/OwO-Network/DeepLX", "message": "DeepL Free API, Developed by sjlleo <i@leo.moe> and missuo <me@missuo.me>. Go to /translate with POST. http://github.com/OwO-Network/DeepLX",
}) })
}) })
// 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{} reqj := ResData{}
c.BindJSON(&reqj) c.BindJSON(&reqj)
// Extracting details from the request JSON
sourceLang := reqj.SourceLang sourceLang := reqj.SourceLang
targetLang := reqj.TargetLang targetLang := reqj.TargetLang
translateText := reqj.TransText translateText := reqj.TransText
// If source language is not specified, auto-detect it
if sourceLang == "" { if sourceLang == "" {
lang := whatlanggo.DetectLang(translateText) lang := whatlanggo.DetectLang(translateText)
deepLLang := strings.ToUpper(lang.Iso6391()) deepLLang := strings.ToUpper(lang.Iso6391())
sourceLang = deepLLang sourceLang = deepLLang
} }
// If target language is not specified, set it to English
if targetLang == "" { if targetLang == "" {
targetLang = "EN" targetLang = "EN"
} }
// Handling empty translation text
if translateText == "" { if translateText == "" {
c.JSON(http.StatusNotFound, gin.H{ c.JSON(http.StatusNotFound, gin.H{
"code": http.StatusNotFound, "code": http.StatusNotFound,
"message": "No Translate Text Found", "message": "No Translate Text Found",
}) })
} else { return
}
// Preparing the request data for the DeepL API
url := "https://www2.deepl.com/jsonrpc" url := "https://www2.deepl.com/jsonrpc"
id = id + 1 id = id + 1
postData := initData(sourceLang, targetLang) postData := initData(sourceLang, targetLang)
@@ -161,22 +181,22 @@ func main() {
Text: translateText, Text: translateText,
RequestAlternatives: 3, RequestAlternatives: 3,
} }
// set id
postData.ID = id postData.ID = id
// set text
postData.Params.Texts = append(postData.Params.Texts, text) postData.Params.Texts = append(postData.Params.Texts, text)
// set timestamp
postData.Params.Timestamp = getTimeStamp(getICount(translateText)) postData.Params.Timestamp = getTimeStamp(getICount(translateText))
// Marshalling the request data to JSON and making necessary string replacements
post_byte, _ := json.Marshal(postData) post_byte, _ := json.Marshal(postData)
postStr := string(post_byte) postStr := string(post_byte)
// add space if necessary // Adding spaces to the JSON string based on the ID to adhere to DeepL's request formatting rules
if (id+5)%29 == 0 || (id+3)%13 == 0 { if (id+5)%29 == 0 || (id+3)%13 == 0 {
postStr = strings.Replace(postStr, "\"method\":\"", "\"method\" : \"", -1) postStr = strings.Replace(postStr, "\"method\":\"", "\"method\" : \"", -1)
} else { } else {
postStr = strings.Replace(postStr, "\"method\":\"", "\"method\": \"", -1) postStr = strings.Replace(postStr, "\"method\":\"", "\"method\": \"", -1)
} }
// Creating a new HTTP POST request with the JSON data as the body
post_byte = []byte(postStr) post_byte = []byte(postStr)
reader := bytes.NewReader(post_byte) reader := bytes.NewReader(post_byte)
request, err := http.NewRequest("POST", url, reader) request, err := http.NewRequest("POST", url, reader)
@@ -185,7 +205,7 @@ func main() {
return return
} }
// Set Headers // Setting HTTP headers to mimic a request from the DeepL iOS App
request.Header.Set("Content-Type", "application/json") request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "*/*") request.Header.Set("Accept", "*/*")
request.Header.Set("x-app-os-name", "iOS") request.Header.Set("x-app-os-name", "iOS")
@@ -198,6 +218,7 @@ func main() {
request.Header.Set("x-app-version", "2.9.1") request.Header.Set("x-app-version", "2.9.1")
request.Header.Set("Connection", "keep-alive") request.Header.Set("Connection", "keep-alive")
// Making the HTTP request to the DeepL API
client := &http.Client{} client := &http.Client{}
resp, err := client.Do(request) resp, err := client.Do(request)
if err != nil { if err != nil {
@@ -206,6 +227,7 @@ func main() {
} }
defer resp.Body.Close() defer resp.Body.Close()
// Handling potential Brotli compressed response body
var bodyReader io.Reader var bodyReader io.Reader
switch resp.Header.Get("Content-Encoding") { switch resp.Header.Get("Content-Encoding") {
case "br": case "br":
@@ -214,13 +236,12 @@ func main() {
bodyReader = resp.Body bodyReader = resp.Body
} }
// Reading the response body and parsing it with gjson
body, err := io.ReadAll(bodyReader) body, err := io.ReadAll(bodyReader)
// body, _ := io.ReadAll(resp.Body) // body, _ := io.ReadAll(resp.Body)
res := gjson.ParseBytes(body) res := gjson.ParseBytes(body)
// display response // Handling various response statuses and potential errors
// fmt.Println(res)
if res.Get("error.code").String() == "-32600" { if res.Get("error.code").String() == "-32600" {
log.Println(res.Get("error").String()) log.Println(res.Get("error").String())
c.JSON(http.StatusNotAcceptable, gin.H{ c.JSON(http.StatusNotAcceptable, gin.H{
@@ -246,10 +267,25 @@ func main() {
"id": id, "id": id,
"data": res.Get("result.texts.0.text").String(), "data": res.Get("result.texts.0.text").String(),
"alternatives": alternatives, "alternatives": alternatives,
"source_lang": sourceLang,
"target_lang": targetLang,
}) })
} }
}
}) })
// by default, listen and serve on 0.0.0.0:1188
// Catch-all route to handle undefined paths
r.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{
"code": http.StatusNotFound,
"message": "Path not found",
})
})
// Determining which port to run the server on, with a fallback to a default port
envPort, ok := os.LookupEnv("PORT")
if ok {
r.Run(":" + envPort)
} else {
r.Run(fmt.Sprintf(":%v", port)) r.Run(fmt.Sprintf(":%v", port))
} }
}