Compare commits

...
20 Commits
Author SHA1 Message Date
Vincent Yang 72beefbebe chore: update toolchain to Go 1.24.5 in go.mod 2025-07-13 23:24:51 +08:00
Vincent Yang 2b0e1e3cbb fix: 503 unable to request. close #196 close #194 close #193 close #191 close #179 close #178 2025-07-13 23:14:24 +08:00
Vincent Yang 8a605887ff refactor: update translation request handling to use new LMT_handle_texts method and improve response processing
- Renamed makeRequest to makeRequestWithBody for clarity.
- Introduced new TextItem and TextResponse types for better structure in translation requests and responses.
- Updated translation logic to handle multiple texts and alternatives.
- Enhanced error handling for blocked requests and translation failures.
- Adjusted timestamp and random number generation for improved request uniqueness.
2025-07-13 23:06:47 +08:00
Vincent Yang 56637adc3c chore: update Go version to 1.24.0 and toolchain to 1.24.2 in go.mod 2025-04-28 17:22:24 -04:00
dependabot[bot] 886853b46f chore(deps): bump golang.org/x/net from 0.36.0 to 0.38.0 (#189)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.36.0 to 0.38.0.
- [Commits](https://github.com/golang/net/compare/v0.36.0...v0.38.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-version: 0.38.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-28 17:20:13 -04:00
dependabot[bot] ceb56a2eee chore(deps): bump github.com/refraction-networking/utls (#188)
Bumps [github.com/refraction-networking/utls](https://github.com/refraction-networking/utls) from 1.6.7 to 1.7.0.
- [Release notes](https://github.com/refraction-networking/utls/releases)
- [Commits](https://github.com/refraction-networking/utls/compare/v1.6.7...v1.7.0)

---
updated-dependencies:
- dependency-name: github.com/refraction-networking/utls
  dependency-version: 1.7.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-28 17:20:05 -04:00
Vincent Yang 4cee0f3031 chore: downgrade Go version to 1.23.0 in go.mod 2025-04-08 15:28:04 -04:00
Vincent Yang cbc3c1be51 chore: remove unused isRichText function 2025-04-08 14:27:33 -04:00
Vincent Yang 84792ead81 chore: bump Go version to 1.24.2 in Dockerfile, go.mod, and CI workflows 2025-04-08 14:27:01 -04:00
Jason Lyu 0a9ff6b582 refactor: make service exportable (#183) 2025-04-08 13:53:20 -04:00
dependabot[bot] d1dbfcc1e5 chore(deps): bump golang.org/x/net from 0.33.0 to 0.36.0 (#181)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.33.0 to 0.36.0.
- [Commits](https://github.com/golang/net/compare/v0.33.0...v0.36.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-21 23:00:40 -04:00
Vincent Yang 2400139a8d fix: unable to translate (switch to DeepL iOS) 2025-03-01 04:24:53 -05:00
Vincent Yang 26a9003b13 bump to Go 1.24.0 2025-02-25 13:16:58 -05:00
Vincent Yang 85fd738f3e bump to Go 1.23.6 2025-02-09 20:12:06 -05:00
Vincent Yang de9888ca5f Upgrade to Go 1.23.5 2025-01-20 17:18:47 -05:00
Vincent Yang bbfb808793 fix: handle line breaks #151 2025-01-20 17:11:53 -05:00
dependabot[bot] 4a77cbf30e chore(deps): bump golang.org/x/net from 0.29.0 to 0.33.0 (#173)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.29.0 to 0.33.0.
- [Commits](https://github.com/golang/net/compare/v0.29.0...v0.33.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-01-20 16:59:52 -05:00
Vincent Young 2d8b84e2c8 Update compose.yaml 2024-12-22 14:18:30 -05:00
dependabot[bot] 1c8beb8a87 chore(deps): bump golang.org/x/crypto from 0.27.0 to 0.31.0 (#166)
Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.27.0 to 0.31.0.
- [Commits](https://github.com/golang/crypto/compare/v0.27.0...v0.31.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-12-12 17:38:43 -05:00
Vincent Young f2fa90208d ci: upgraded to Go 1.23.4 2024-12-05 13:13:40 -05:00
12 changed files with 450 additions and 485 deletions
+1 -1
View File
@@ -15,7 +15,7 @@ jobs:
- name: Set up Go - name: Set up Go
uses: actions/setup-go@v4 uses: actions/setup-go@v4
with: with:
go-version: '1.23.3' go-version: '1.24.2'
- name: Install golint - name: Install golint
run: go install golang.org/x/lint/golint@latest run: go install golang.org/x/lint/golint@latest
+1 -1
View File
@@ -15,7 +15,7 @@ jobs:
- uses: actions/setup-go@v4 - uses: actions/setup-go@v4
with: with:
go-version: "1.23.3" go-version: "1.24.2"
- run: bash .cross_compile.sh - run: bash .cross_compile.sh
+1 -1
View File
@@ -1,4 +1,4 @@
FROM golang:1.23.3 AS builder FROM golang:1.24.2 AS builder
WORKDIR /go/src/github.com/OwO-Network/DeepLX WORKDIR /go/src/github.com/OwO-Network/DeepLX
COPY . . COPY . .
RUN go get -d -v ./ RUN go get -d -v ./
-2
View File
@@ -1,5 +1,3 @@
version: '3.8'
services: services:
deeplx: deeplx:
image: ghcr.io/owo-network/deeplx:latest image: ghcr.io/owo-network/deeplx:latest
+10 -8
View File
@@ -1,6 +1,8 @@
module github.com/OwO-Network/DeepLX module github.com/OwO-Network/DeepLX
go 1.23.3 go 1.24.0
toolchain go1.24.5
require ( require (
github.com/abadojack/whatlanggo v1.0.1 github.com/abadojack/whatlanggo v1.0.1
@@ -15,7 +17,7 @@ require (
github.com/bytedance/sonic v1.11.2 // indirect github.com/bytedance/sonic v1.11.2 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
github.com/chenzhuoyu/iasm v0.9.1 // indirect github.com/chenzhuoyu/iasm v0.9.1 // indirect
github.com/cloudflare/circl v1.4.0 // indirect github.com/cloudflare/circl v1.5.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/locales v0.14.1 // indirect
@@ -38,20 +40,20 @@ require (
github.com/pelletier/go-toml/v2 v2.1.1 // indirect github.com/pelletier/go-toml/v2 v2.1.1 // indirect
github.com/quic-go/qpack v0.5.1 // indirect github.com/quic-go/qpack v0.5.1 // indirect
github.com/quic-go/quic-go v0.48.2 // indirect github.com/quic-go/quic-go v0.48.2 // indirect
github.com/refraction-networking/utls v1.6.7 // indirect github.com/refraction-networking/utls v1.7.0 // indirect
github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect github.com/tidwall/pretty v1.2.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect github.com/ugorji/go/codec v1.2.12 // indirect
go.uber.org/mock v0.4.0 // indirect go.uber.org/mock v0.4.0 // indirect
golang.org/x/arch v0.7.0 // indirect golang.org/x/arch v0.7.0 // indirect
golang.org/x/crypto v0.27.0 // indirect golang.org/x/crypto v0.36.0 // indirect
golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 // indirect golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 // indirect
golang.org/x/mod v0.21.0 // indirect golang.org/x/mod v0.21.0 // indirect
golang.org/x/net v0.29.0 // indirect golang.org/x/net v0.38.0 // indirect
golang.org/x/sync v0.8.0 // indirect golang.org/x/sync v0.12.0 // indirect
golang.org/x/sys v0.25.0 // indirect golang.org/x/sys v0.31.0 // indirect
golang.org/x/text v0.18.0 // indirect golang.org/x/text v0.23.0 // indirect
golang.org/x/tools v0.25.0 // indirect golang.org/x/tools v0.25.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
+14 -14
View File
@@ -13,8 +13,8 @@ github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpV
github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog=
github.com/chenzhuoyu/iasm v0.9.1 h1:tUHQJXo3NhBqw6s33wkGn9SP3bvrWLdlVIJ3hQBL7P0= github.com/chenzhuoyu/iasm v0.9.1 h1:tUHQJXo3NhBqw6s33wkGn9SP3bvrWLdlVIJ3hQBL7P0=
github.com/chenzhuoyu/iasm v0.9.1/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= github.com/chenzhuoyu/iasm v0.9.1/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog=
github.com/cloudflare/circl v1.4.0 h1:BV7h5MgrktNzytKmWjpOtdYrf0lkkbF8YMlBGPhJQrY= github.com/cloudflare/circl v1.5.0 h1:hxIWksrX6XN5a1L2TI/h53AGPhNHoUBo+TD1ms9+pys=
github.com/cloudflare/circl v1.4.0/go.mod h1:PDRU+oXvdD7KCtgKxW95M5Z8BpSCJXQORiZFnBQS5QU= github.com/cloudflare/circl v1.5.0/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
@@ -86,8 +86,8 @@ github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg= github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
github.com/quic-go/quic-go v0.48.2 h1:wsKXZPeGWpMpCGSWqOcqpW2wZYic/8T3aqiOID0/KWE= github.com/quic-go/quic-go v0.48.2 h1:wsKXZPeGWpMpCGSWqOcqpW2wZYic/8T3aqiOID0/KWE=
github.com/quic-go/quic-go v0.48.2/go.mod h1:yBgs3rWBOADpga7F+jJsb6Ybg1LSYiQvwWlLX+/6HMs= github.com/quic-go/quic-go v0.48.2/go.mod h1:yBgs3rWBOADpga7F+jJsb6Ybg1LSYiQvwWlLX+/6HMs=
github.com/refraction-networking/utls v1.6.7 h1:zVJ7sP1dJx/WtVuITug3qYUq034cDq9B2MR1K67ULZM= github.com/refraction-networking/utls v1.7.0 h1:9JTnze/Md74uS3ZWiRAabityY0un69rOLXsBf8LGgTs=
github.com/refraction-networking/utls v1.6.7/go.mod h1:BC3O4vQzye5hqpmDTWUqi4P5DDhzJfkV1tdqtawQIH0= github.com/refraction-networking/utls v1.7.0/go.mod h1:lV0Gwc1/Fi+HYH8hOtgFRdHfKo4FKSn6+FdyOz9hRms=
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
@@ -116,22 +116,22 @@ go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc= golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc=
golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A= golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 h1:e66Fs6Z+fZTbFBAxKfP3PALWBtpfqks2bwGcexMxgtk= golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 h1:e66Fs6Z+fZTbFBAxKfP3PALWBtpfqks2bwGcexMxgtk=
golang.org/x/exp v0.0.0-20240909161429-701f63a606c0/go.mod h1:2TbTHSBQa924w8M6Xs1QcRcFwyucIwBGpK1p2f1YFFY= golang.org/x/exp v0.0.0-20240909161429-701f63a606c0/go.mod h1:2TbTHSBQa924w8M6Xs1QcRcFwyucIwBGpK1p2f1YFFY=
golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0= golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0=
golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo= golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0= golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.25.0 h1:oFU9pkj/iJgs+0DT+VMHrx+oBKs/LJMV+Uvg78sl+fE= golang.org/x/tools v0.25.0 h1:oFU9pkj/iJgs+0DT+VMHrx+oBKs/LJMV+Uvg78sl+fE=
+7 -254
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: Jason Lyu
* @LastEditTime: 2024-11-01 13:04:50 * @LastEditTime: 2025-04-08 13:45:00
* @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
@@ -14,268 +14,21 @@ package main
import ( import (
"fmt" "fmt"
"log"
"net/http"
"net/url"
"os"
"strings"
translate "github.com/OwO-Network/DeepLX/translate"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/OwO-Network/DeepLX/service"
) )
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()
}
}
type PayloadFree struct {
TransText string `json:"text"`
SourceLang string `json:"source_lang"`
TargetLang string `json:"target_lang"`
TagHandling string `json:"tag_handling"`
}
type PayloadAPI struct {
Text []string `json:"text"`
TargetLang string `json:"target_lang"`
SourceLang string `json:"source_lang"`
TagHandling string `json:"tag_handling"`
}
func main() { func main() {
cfg := initConfig() cfg := service.InitConfig()
fmt.Printf("DeepL X has been successfully launched! Listening on %v:%v\n", cfg.IP, cfg.Port) fmt.Printf("DeepL X has been successfully launched! Listening on %v:%v\n", cfg.IP, 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>.")
// 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.")
}
// Setting the application to release mode // Setting the application to release mode
gin.SetMode(gin.ReleaseMode) gin.SetMode(gin.ReleaseMode)
r := gin.Default()
r.Use(cors.Default())
// Defining the root endpoint which returns the project details app := service.Router(cfg)
r.GET("/", func(c *gin.Context) { app.Run(fmt.Sprintf("%v:%v", cfg.IP, cfg.Port))
c.JSON(http.StatusOK, gin.H{
"code": http.StatusOK,
"message": "DeepL Free API, Developed by sjlleo and missuo. Go to /translate with POST. http://github.com/OwO-Network/DeepLX",
})
})
// Free API endpoint, No Pro Account required
r.POST("/translate", authMiddleware(cfg), func(c *gin.Context) {
req := PayloadFree{}
c.BindJSON(&req)
sourceLang := req.SourceLang
targetLang := req.TargetLang
translateText := req.TransText
tagHandling := req.TagHandling
proxyURL := cfg.Proxy
if tagHandling != "" && tagHandling != "html" && tagHandling != "xml" {
c.JSON(http.StatusBadRequest, gin.H{
"code": http.StatusBadRequest,
"message": "Invalid tag_handling value. Allowed values are 'html' and 'xml'.",
})
return
}
result, err := translate.TranslateByDeepLX(sourceLang, targetLang, translateText, tagHandling, proxyURL, "")
if err != nil {
log.Fatalf("Translation failed: %s", err)
}
if result.Code == http.StatusOK {
c.JSON(http.StatusOK, 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,
})
} else {
c.JSON(result.Code, gin.H{
"code": result.Code,
"message": result.Message,
})
}
})
// Pro API endpoint, Pro Account required
r.POST("/v1/translate", authMiddleware(cfg), func(c *gin.Context) {
req := PayloadFree{}
c.BindJSON(&req)
sourceLang := req.SourceLang
targetLang := req.TargetLang
translateText := req.TransText
tagHandling := req.TagHandling
proxyURL := cfg.Proxy
dlSession := cfg.DlSession
if tagHandling != "" && tagHandling != "html" && tagHandling != "xml" {
c.JSON(http.StatusBadRequest, gin.H{
"code": http.StatusBadRequest,
"message": "Invalid tag_handling value. Allowed values are 'html' and 'xml'.",
})
return
}
cookie := c.GetHeader("Cookie")
if cookie != "" {
dlSession = strings.Replace(cookie, "dl_session=", "", -1)
}
if dlSession == "" {
c.JSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"message": "No dl_session Found",
})
return
} else if strings.Contains(dlSession, ".") {
c.JSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"message": "Your account is not a Pro account. Please upgrade your account or switch to a different account.",
})
return
}
result, err := translate.TranslateByDeepLX(sourceLang, targetLang, translateText, tagHandling, proxyURL, dlSession)
if err != nil {
log.Fatalf("Translation failed: %s", err)
}
if result.Code == http.StatusOK {
c.JSON(http.StatusOK, 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,
})
} else {
c.JSON(result.Code, gin.H{
"code": result.Code,
"message": result.Message,
})
}
})
// Free API endpoint, Consistent with the official API format
r.POST("/v2/translate", authMiddleware(cfg), func(c *gin.Context) {
proxyURL := cfg.Proxy
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 := translate.TranslateByDeepLX("", targetLang, translateText, "", proxyURL, "")
if err != nil {
log.Fatalf("Translation failed: %s", err)
}
if result.Code == http.StatusOK {
c.JSON(http.StatusOK, gin.H{
"translations": []map[string]interface{}{
{
"detected_source_language": result.SourceLang,
"text": result.Data,
},
},
})
} else {
c.JSON(result.Code, gin.H{
"code": result.Code,
"message": result.Message,
})
}
})
// 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",
})
})
r.Run(fmt.Sprintf("%v:%v", cfg.IP, cfg.Port))
} }
+4 -4
View File
@@ -1,8 +1,8 @@
/* /*
* @Author: Vincent Yang * @Author: Vincent Yang
* @Date: 2024-04-23 00:39:03 * @Date: 2024-04-23 00:39:03
* @LastEditors: Vincent Yang * @LastEditors: Jason Lyu
* @LastEditTime: 2024-09-17 19:34:32 * @LastEditTime: 2025-04-08 13:45:00
* @FilePath: /DeepLX/config.go * @FilePath: /DeepLX/config.go
* @Telegram: https://t.me/missuo * @Telegram: https://t.me/missuo
* @GitHub: https://github.com/missuo * @GitHub: https://github.com/missuo
@@ -10,7 +10,7 @@
* Copyright © 2024 by Vincent, All Rights Reserved. * Copyright © 2024 by Vincent, All Rights Reserved.
*/ */
package main package service
import ( import (
"flag" "flag"
@@ -26,7 +26,7 @@ type Config struct {
Proxy string Proxy string
} }
func initConfig() *Config { func InitConfig() *Config {
cfg := &Config{ cfg := &Config{
IP: "0.0.0.0", IP: "0.0.0.0",
Port: 1188, Port: 1188,
+275
View File
@@ -0,0 +1,275 @@
/*
* @Author: Vincent Yang
* @Date: 2023-07-01 21:45:34
* @LastEditors: Jason Lyu
* @LastEditTime: 2025-04-08 13:45:00
* @FilePath: /DeepLX/main.go
* @Telegram: https://t.me/missuo
* @GitHub: https://github.com/missuo
*
* Copyright © 2024 by Vincent, All Rights Reserved.
*/
package service
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
"strings"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/OwO-Network/DeepLX/translate"
)
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()
}
}
type PayloadFree struct {
TransText string `json:"text"`
SourceLang string `json:"source_lang"`
TargetLang string `json:"target_lang"`
TagHandling string `json:"tag_handling"`
}
type PayloadAPI struct {
Text []string `json:"text"`
TargetLang string `json:"target_lang"`
SourceLang string `json:"source_lang"`
TagHandling string `json:"tag_handling"`
}
func Router(cfg *Config) *gin.Engine {
// 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.")
}
r := gin.Default()
r.Use(cors.Default())
// Defining the root endpoint which returns the project details
r.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"code": http.StatusOK,
"message": "DeepL Free API, Developed by sjlleo and missuo. Go to /translate with POST. http://github.com/OwO-Network/DeepLX",
})
})
// Free API endpoint, No Pro Account required
r.POST("/translate", authMiddleware(cfg), func(c *gin.Context) {
req := PayloadFree{}
c.BindJSON(&req)
sourceLang := req.SourceLang
targetLang := req.TargetLang
translateText := req.TransText
tagHandling := req.TagHandling
proxyURL := cfg.Proxy
if tagHandling != "" && tagHandling != "html" && tagHandling != "xml" {
c.JSON(http.StatusBadRequest, gin.H{
"code": http.StatusBadRequest,
"message": "Invalid tag_handling value. Allowed values are 'html' and 'xml'.",
})
return
}
result, err := translate.TranslateByDeepLX(sourceLang, targetLang, translateText, tagHandling, proxyURL, "")
if err != nil {
log.Fatalf("Translation failed: %s", err)
}
if result.Code == http.StatusOK {
c.JSON(http.StatusOK, 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,
})
} else {
c.JSON(result.Code, gin.H{
"code": result.Code,
"message": result.Message,
})
}
})
// Pro API endpoint, Pro Account required
r.POST("/v1/translate", authMiddleware(cfg), func(c *gin.Context) {
req := PayloadFree{}
c.BindJSON(&req)
sourceLang := req.SourceLang
targetLang := req.TargetLang
translateText := req.TransText
tagHandling := req.TagHandling
proxyURL := cfg.Proxy
dlSession := cfg.DlSession
if tagHandling != "" && tagHandling != "html" && tagHandling != "xml" {
c.JSON(http.StatusBadRequest, gin.H{
"code": http.StatusBadRequest,
"message": "Invalid tag_handling value. Allowed values are 'html' and 'xml'.",
})
return
}
cookie := c.GetHeader("Cookie")
if cookie != "" {
dlSession = strings.Replace(cookie, "dl_session=", "", -1)
}
if dlSession == "" {
c.JSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"message": "No dl_session Found",
})
return
} else if strings.Contains(dlSession, ".") {
c.JSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"message": "Your account is not a Pro account. Please upgrade your account or switch to a different account.",
})
return
}
result, err := translate.TranslateByDeepLX(sourceLang, targetLang, translateText, tagHandling, proxyURL, dlSession)
if err != nil {
log.Fatalf("Translation failed: %s", err)
}
if result.Code == http.StatusOK {
c.JSON(http.StatusOK, 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,
})
} else {
c.JSON(result.Code, gin.H{
"code": result.Code,
"message": result.Message,
})
}
})
// Free API endpoint, Consistent with the official API format
r.POST("/v2/translate", authMiddleware(cfg), func(c *gin.Context) {
proxyURL := cfg.Proxy
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 := translate.TranslateByDeepLX("", targetLang, translateText, "", proxyURL, "")
if err != nil {
log.Fatalf("Translation failed: %s", err)
}
if result.Code == http.StatusOK {
c.JSON(http.StatusOK, gin.H{
"translations": []map[string]interface{}{
{
"detected_source_language": result.SourceLang,
"text": result.Data,
},
},
})
} else {
c.JSON(result.Code, gin.H{
"code": result.Code,
"message": result.Message,
})
}
})
// 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",
})
})
return r
}
+70 -156
View File
@@ -2,7 +2,7 @@
* @Author: Vincent Young * @Author: Vincent Young
* @Date: 2024-09-16 11:59:24 * @Date: 2024-09-16 11:59:24
* @LastEditors: Vincent Yang * @LastEditors: Vincent Yang
* @LastEditTime: 2024-12-03 11:23:23 * @LastEditTime: 2025-07-13 23:09:49
* @FilePath: /DeepLX/translate/translate.go * @FilePath: /DeepLX/translate/translate.go
* @Telegram: https://t.me/missuo * @Telegram: https://t.me/missuo
* @GitHub: https://github.com/missuo * @GitHub: https://github.com/missuo
@@ -14,6 +14,8 @@ package translate
import ( import (
"bytes" "bytes"
"compress/flate"
"compress/gzip"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@@ -27,35 +29,16 @@ import (
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
) )
const baseURL = "https://www2.deepl.com/jsonrpc" // makeRequestWithBody makes an HTTP request with pre-formatted body using minimal headers
func makeRequestWithBody(postStr string, proxyURL string, dlSession string) (gjson.Result, error) {
// makeRequest makes an HTTP request to DeepL API urlFull := "https://www2.deepl.com/jsonrpc"
func makeRequest(postData *PostData, urlMethod string, proxyURL string, dlSession string) (gjson.Result, error) {
urlFull := fmt.Sprintf("%s?client=chrome-extension,1.28.0&method=%s", baseURL, urlMethod)
postStr := formatPostString(postData)
// Create a new req client // Create a new req client
client := req.C().SetTLSFingerprintRandomized() client := req.C().SetTLSFingerprintRandomized()
// Set headers // Set minimal headers like TypeScript version
headers := http.Header{ headers := http.Header{
"Accept": []string{"*/*"}, "Content-Type": []string{"application/json"},
"Accept-Language": []string{"en-US,en;q=0.9,zh-CN;q=0.8,zh-TW;q=0.7,zh-HK;q=0.6,zh;q=0.5"},
"Authorization": []string{"None"},
"Cache-Control": []string{"no-cache"},
"Content-Type": []string{"application/json"},
"DNT": []string{"1"},
"Origin": []string{"chrome-extension://cofdbpoegempjloogbagkncekinflcnj"},
"Pragma": []string{"no-cache"},
"Priority": []string{"u=1, i"},
"Referer": []string{"https://www.deepl.com/"},
"Sec-Fetch-Dest": []string{"empty"},
"Sec-Fetch-Mode": []string{"cors"},
"Sec-Fetch-Site": []string{"none"},
"Sec-GPC": []string{"1"},
"User-Agent": []string{"DeepLBrowserExtension/1.28.0 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36"},
} }
if dlSession != "" { if dlSession != "" {
@@ -82,41 +65,34 @@ func makeRequest(postData *PostData, urlMethod string, proxyURL string, dlSessio
return gjson.Result{}, err return gjson.Result{}, err
} }
// Check for blocked status like TypeScript version
if resp.StatusCode == 429 {
return gjson.Result{}, fmt.Errorf("too many requests, your IP has been blocked by DeepL temporarily, please don't request it frequently in a short time")
}
var bodyReader io.Reader var bodyReader io.Reader
if resp.Header.Get("Content-Encoding") == "br" { contentEncoding := resp.Header.Get("Content-Encoding")
switch contentEncoding {
case "br":
bodyReader = brotli.NewReader(resp.Body) bodyReader = brotli.NewReader(resp.Body)
} else { case "gzip":
bodyReader, err = gzip.NewReader(resp.Body)
if err != nil {
return gjson.Result{}, fmt.Errorf("failed to create gzip reader: %w", err)
}
case "deflate":
bodyReader = flate.NewReader(resp.Body)
default:
bodyReader = resp.Body bodyReader = resp.Body
} }
body, err := io.ReadAll(bodyReader) body, err := io.ReadAll(bodyReader)
if err != nil { if err != nil {
return gjson.Result{}, err return gjson.Result{}, fmt.Errorf("failed to read response body: %w", err)
} }
return gjson.ParseBytes(body), nil return gjson.ParseBytes(body), nil
} }
// splitText splits the input text for translation
func splitText(text string, tagHandling bool, proxyURL string, dlSession string) (gjson.Result, error) {
postData := &PostData{
Jsonrpc: "2.0",
Method: "LMT_split_text",
ID: getRandomNumber(),
Params: Params{
CommonJobParams: CommonJobParams{
Mode: "translate",
},
Lang: Lang{
LangUserSelected: "auto",
},
Texts: []string{text},
TextType: map[bool]string{true: "richtext", false: "plaintext"}[tagHandling || isRichText(text)],
},
}
return makeRequest(postData, "LMT_split_text", proxyURL, dlSession)
}
// TranslateByDeepLX performs translation using DeepL API // TranslateByDeepLX performs translation using DeepL API
func TranslateByDeepLX(sourceLang, targetLang, text string, tagHandling string, proxyURL string, dlSession string) (DeepLXTranslationResult, error) { func TranslateByDeepLX(sourceLang, targetLang, text string, tagHandling string, proxyURL string, dlSession string) (DeepLXTranslationResult, error) {
if text == "" { if text == "" {
@@ -126,101 +102,40 @@ func TranslateByDeepLX(sourceLang, targetLang, text string, tagHandling string,
}, nil }, nil
} }
// Split text first
splitResult, err := splitText(text, tagHandling == "html" || tagHandling == "xml", proxyURL, dlSession)
if err != nil {
return DeepLXTranslationResult{
Code: http.StatusServiceUnavailable,
Message: err.Error(),
}, nil
}
// Get detected language if source language is auto // Get detected language if source language is auto
if sourceLang == "auto" || sourceLang == "" { if sourceLang == "auto" || sourceLang == "" {
sourceLang = strings.ToUpper(whatlanggo.DetectLang(text).Iso6391()) sourceLang = strings.ToUpper(whatlanggo.DetectLang(text).Iso6391())
} }
// Prepare jobs from split result // Prepare translation request using new LMT_handle_texts method
var jobs []Job
chunks := splitResult.Get("result.texts.0.chunks").Array()
for idx, chunk := range chunks {
sentence := chunk.Get("sentences.0")
// Handle context
contextBefore := []string{}
contextAfter := []string{}
if idx > 0 {
contextBefore = []string{chunks[idx-1].Get("sentences.0.text").String()}
}
if idx < len(chunks)-1 {
contextAfter = []string{chunks[idx+1].Get("sentences.0.text").String()}
}
jobs = append(jobs, Job{
Kind: "default",
PreferredNumBeams: 4,
RawEnContextBefore: contextBefore,
RawEnContextAfter: contextAfter,
Sentences: []Sentence{{
Prefix: sentence.Get("prefix").String(),
Text: sentence.Get("text").String(),
ID: idx + 1,
}},
})
}
hasRegionalVariant := false
targetLangCode := targetLang
targetLangParts := strings.Split(targetLang, "-")
if len(targetLangParts) > 1 {
targetLangCode = targetLangParts[0]
hasRegionalVariant = true
}
// Prepare translation request
id := getRandomNumber() id := getRandomNumber()
iCount := getICount(text)
timestamp := getTimeStamp(iCount)
postData := &PostData{ postData := &PostData{
Jsonrpc: "2.0", Jsonrpc: "2.0",
Method: "LMT_handle_jobs", Method: "LMT_handle_texts",
ID: id, ID: id,
Params: Params{ Params: Params{
CommonJobParams: CommonJobParams{ Splitting: "newlines",
Mode: "translate",
},
Lang: Lang{ Lang: Lang{
SourceLangComputed: strings.ToUpper(sourceLang), SourceLangUserSelected: sourceLang,
TargetLang: strings.ToUpper(targetLangCode), TargetLang: targetLang,
}, },
Jobs: jobs, Texts: []TextItem{{
Priority: 1, Text: text,
Timestamp: getTimeStamp(getICount(text)), RequestAlternatives: 3,
}},
Timestamp: timestamp,
}, },
} }
if hasRegionalVariant { // Format and apply body manipulation method like TypeScript
postData = &PostData{ postStr := formatPostString(postData)
Jsonrpc: "2.0", postStr = handlerBodyMethod(id, postStr)
Method: "LMT_handle_jobs",
ID: id,
Params: Params{
CommonJobParams: CommonJobParams{
Mode: "translate",
RegionalVariant: map[bool]string{true: targetLang, false: ""}[hasRegionalVariant],
},
Lang: Lang{
SourceLangComputed: strings.ToUpper(sourceLang),
TargetLang: strings.ToUpper(targetLangCode),
},
Jobs: jobs,
Priority: 1,
Timestamp: getTimeStamp(getICount(text)),
},
}
}
// Make translation request // Make translation request
result, err := makeRequest(postData, "LMT_handle_jobs", proxyURL, dlSession) result, err := makeRequestWithBody(postStr, proxyURL, dlSession)
if err != nil { if err != nil {
return DeepLXTranslationResult{ return DeepLXTranslationResult{
Code: http.StatusServiceUnavailable, Code: http.StatusServiceUnavailable,
@@ -228,45 +143,44 @@ func TranslateByDeepLX(sourceLang, targetLang, text string, tagHandling string,
}, nil }, nil
} }
// Process translation results // Process translation results using new format
var alternatives []string textsArray := result.Get("result.texts").Array()
var translatedText string if len(textsArray) == 0 {
translations := result.Get("result.translations").Array()
if len(translations) > 0 {
// Get alternatives
numBeams := len(translations[0].Get("beams").Array())
for i := 0; i < numBeams; i++ {
var altText string
for _, translation := range translations {
beams := translation.Get("beams").Array()
if i < len(beams) {
altText += beams[i].Get("sentences.0.text").String()
}
}
if altText != "" {
alternatives = append(alternatives, altText)
}
}
// Get main translation
for _, translation := range translations {
translatedText += translation.Get("beams.0.sentences.0.text").String() + " "
}
translatedText = strings.TrimSpace(translatedText)
}
if translatedText == "" {
return DeepLXTranslationResult{ return DeepLXTranslationResult{
Code: http.StatusServiceUnavailable, Code: http.StatusServiceUnavailable,
Message: "Translation failed", Message: "Translation failed",
}, nil }, nil
} }
// Get main translation
mainText := textsArray[0].Get("text").String()
if mainText == "" {
return DeepLXTranslationResult{
Code: http.StatusServiceUnavailable,
Message: "Translation failed",
}, nil
}
// Get alternatives
var alternatives []string
alternativesArray := textsArray[0].Get("alternatives").Array()
for _, alt := range alternativesArray {
altText := alt.Get("text").String()
if altText != "" {
alternatives = append(alternatives, altText)
}
}
// Get detected source language from response
detectedLang := result.Get("result.lang").String()
if detectedLang != "" {
sourceLang = detectedLang
}
return DeepLXTranslationResult{ return DeepLXTranslationResult{
Code: http.StatusOK, Code: http.StatusOK,
ID: id, ID: id,
Data: translatedText, Data: mainText,
Alternatives: alternatives, Alternatives: alternatives,
SourceLang: sourceLang, SourceLang: sourceLang,
TargetLang: targetLang, TargetLang: targetLang,
+56 -30
View File
@@ -2,7 +2,7 @@
* @Author: Vincent Young * @Author: Vincent Young
* @Date: 2024-09-16 11:59:24 * @Date: 2024-09-16 11:59:24
* @LastEditors: Vincent Yang * @LastEditors: Vincent Yang
* @LastEditTime: 2024-11-01 23:18:56 * @LastEditTime: 2025-03-01 04:16:07
* @FilePath: /DeepLX/translate/types.go * @FilePath: /DeepLX/translate/types.go
* @Telegram: https://t.me/missuo * @Telegram: https://t.me/missuo
* @GitHub: https://github.com/missuo * @GitHub: https://github.com/missuo
@@ -14,14 +14,19 @@ package translate
// Lang represents the language settings for translation // Lang represents the language settings for translation
type Lang struct { type Lang struct {
SourceLangComputed string `json:"source_lang_computed,omitempty"` SourceLangUserSelected string `json:"source_lang_user_selected"` // Can be "auto"
TargetLang string `json:"target_lang"` TargetLang string `json:"target_lang"`
LangUserSelected string `json:"lang_user_selected,omitempty"` SourceLangComputed string `json:"source_lang_computed,omitempty"`
} }
// CommonJobParams represents common parameters for translation jobs // CommonJobParams represents common parameters for translation jobs
type CommonJobParams struct { type CommonJobParams struct {
Formality string `json:"formality"` // Can be "undefined"
TranscribeAs string `json:"transcribe_as"`
Mode string `json:"mode"` Mode string `json:"mode"`
WasSpoken bool `json:"wasSpoken"`
AdvancedMode bool `json:"advancedMode"`
TextType string `json:"textType"`
RegionalVariant string `json:"regionalVariant,omitempty"` RegionalVariant string `json:"regionalVariant,omitempty"`
} }
@@ -41,14 +46,25 @@ type Job struct {
Sentences []Sentence `json:"sentences"` Sentences []Sentence `json:"sentences"`
} }
// TextItem represents a text item for translation
type TextItem struct {
Text string `json:"text"`
RequestAlternatives int `json:"requestAlternatives"`
}
// Params represents parameters for translation requests // Params represents parameters for translation requests
type Params struct { type Params struct {
Splitting string `json:"splitting"`
Lang Lang `json:"lang"`
Texts []TextItem `json:"texts"`
Timestamp int64 `json:"timestamp"`
}
// LegacyParams represents the old parameters structure for jobs (kept for compatibility)
type LegacyParams struct {
CommonJobParams CommonJobParams `json:"commonJobParams"` CommonJobParams CommonJobParams `json:"commonJobParams"`
Lang Lang `json:"lang"` Lang Lang `json:"lang"`
Texts []string `json:"texts,omitempty"` Jobs []Job `json:"jobs"`
TextType string `json:"textType,omitempty"`
Jobs []Job `json:"jobs,omitempty"`
Priority int `json:"priority,omitempty"`
Timestamp int64 `json:"timestamp"` Timestamp int64 `json:"timestamp"`
} }
@@ -60,49 +76,59 @@ type PostData struct {
Params Params `json:"params"` Params Params `json:"params"`
} }
// SplitTextResponse represents the response from text splitting // TextResponse represents a single text response
type SplitTextResponse struct { type TextResponse struct {
Text string `json:"text"`
Alternatives []struct {
Text string `json:"text"`
} `json:"alternatives"`
}
// TranslationResponse represents the response from LMT_handle_texts
type TranslationResponse struct {
Jsonrpc string `json:"jsonrpc"` Jsonrpc string `json:"jsonrpc"`
ID int64 `json:"id"` ID int64 `json:"id"`
Result struct { Result struct {
Lang struct { Lang string `json:"lang"`
Detected string `json:"detected"` Texts []TextResponse `json:"texts"`
} `json:"lang"`
Texts []struct {
Chunks []struct {
Sentences []struct {
Prefix string `json:"prefix"`
Text string `json:"text"`
} `json:"sentences"`
} `json:"chunks"`
} `json:"texts"`
} `json:"result"` } `json:"result"`
} }
// TranslationResponse represents the response from translation // LegacyTranslationResponse represents the old response format (kept for compatibility)
type TranslationResponse struct { type LegacyTranslationResponse struct {
Jsonrpc string `json:"jsonrpc"` Jsonrpc string `json:"jsonrpc"`
ID int64 `json:"id"` ID int64 `json:"id"`
Result struct { Result struct {
Translations []struct { Translations []struct {
Beams []struct { Beams []struct {
Sentences []struct { Sentences []SentenceResponse `json:"sentences"`
Text string `json:"text"` NumSymbols int `json:"num_symbols"`
} `json:"sentences"` RephraseVariant struct { // Added rephrase_variant
Name string `json:"name"`
} `json:"rephrase_variant"`
} `json:"beams"` } `json:"beams"`
Quality string `json:"quality"` // Added quality
} `json:"translations"` } `json:"translations"`
SourceLang string `json:"source_lang"` TargetLang string `json:"target_lang"`
TargetLang string `json:"target_lang"` SourceLang string `json:"source_lang"`
SourceLangIsConfident bool `json:"source_lang_is_confident"`
DetectedLanguages map[string]interface{} `json:"detectedLanguages"` // Use interface{} for now
} `json:"result"` } `json:"result"`
} }
// SentenceResponse is a helper struct for the response sentences
type SentenceResponse struct {
Text string `json:"text"`
IDS []int `json:"ids"` // Added IDS
}
// DeepLXTranslationResult represents the final translation result // DeepLXTranslationResult represents the final translation result
type DeepLXTranslationResult struct { type DeepLXTranslationResult struct {
Code int `json:"code"` Code int `json:"code"`
ID int64 `json:"id"` ID int64 `json:"id"`
Message string `json:"message,omitempty"` Message string `json:"message,omitempty"`
Data string `json:"data"` Data string `json:"data"` // The primary translated text
Alternatives []string `json:"alternatives"` Alternatives []string `json:"alternatives"` // Other possible translations
SourceLang string `json:"source_lang"` SourceLang string `json:"source_lang"`
TargetLang string `json:"target_lang"` TargetLang string `json:"target_lang"`
Method string `json:"method"` Method string `json:"method"`
+10 -13
View File
@@ -2,7 +2,7 @@
* @Author: Vincent Young * @Author: Vincent Young
* @Date: 2024-09-16 11:59:24 * @Date: 2024-09-16 11:59:24
* @LastEditors: Vincent Yang * @LastEditors: Vincent Yang
* @LastEditTime: 2024-11-01 00:39:32 * @LastEditTime: 2025-04-08 14:27:21
* @FilePath: /DeepLX/translate/utils.go * @FilePath: /DeepLX/translate/utils.go
* @Telegram: https://t.me/missuo * @Telegram: https://t.me/missuo
* @GitHub: https://github.com/missuo * @GitHub: https://github.com/missuo
@@ -28,7 +28,7 @@ func getICount(translateText string) int64 {
func getRandomNumber() int64 { func getRandomNumber() int64 {
src := rand.NewSource(time.Now().UnixNano()) src := rand.NewSource(time.Now().UnixNano())
rng := rand.New(src) rng := rand.New(src)
num := rng.Int63n(99999) + 8300000 num := rng.Int63n(99999) + 100000
return num * 1000 return num * 1000
} }
@@ -37,7 +37,7 @@ func getTimeStamp(iCount int64) int64 {
ts := time.Now().UnixMilli() ts := time.Now().UnixMilli()
if iCount != 0 { if iCount != 0 {
iCount = iCount + 1 iCount = iCount + 1
return ts - ts%iCount + iCount return ts - (ts % iCount) + iCount
} }
return ts return ts
} }
@@ -46,17 +46,14 @@ func getTimeStamp(iCount int64) int64 {
func formatPostString(postData *PostData) string { func formatPostString(postData *PostData) string {
postBytes, _ := json.Marshal(postData) postBytes, _ := json.Marshal(postData)
postStr := string(postBytes) postStr := string(postBytes)
if (postData.ID+5)%29 == 0 || (postData.ID+3)%13 == 0 {
postStr = strings.Replace(postStr, `"method":"`, `"method" : "`, 1)
} else {
postStr = strings.Replace(postStr, `"method":"`, `"method": "`, 1)
}
return postStr return postStr
} }
// isRichText checks if text contains HTML-like tags // handlerBodyMethod manipulates the request body based on random number calculation
func isRichText(text string) bool { func handlerBodyMethod(random int64, body string) string {
return strings.Contains(text, "<") && strings.Contains(text, ">") calc := (random+5)%29 == 0 || (random+3)%13 == 0
if calc {
return strings.Replace(body, `"method":"`, `"method" : "`, 1)
}
return strings.Replace(body, `"method":"`, `"method": "`, 1)
} }