Skip to content

Commit

Permalink
仓库初始提交
Browse files Browse the repository at this point in the history
  • Loading branch information
guobao2333 committed Aug 8, 2024
0 parents commit b6c1f9d
Show file tree
Hide file tree
Showing 9 changed files with 300 additions and 0 deletions.
19 changes: 19 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# git
.git/

# backup
*.bak

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

node_modules/

yarn.lock
package-lock.json
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 guobao2333

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
80 changes: 80 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# DeepLX Serverless

DeepLX 免费翻译API**函数部署版**,与[原项目DeepLX](https://github.com/OwO-Network/DeepLX)的区别在于**利用了云函数的请求IP不固定的特性,极大程度上避免了`429`请求太频繁报错**

## Usage | 用法

### Prerequisites | 你需要准备什么

- 一双灵活的小手
- 一个聪明的脑袋瓜
- 一个云函数服务器

### Deploy | 部署

使用任意支持云函数部署的服务器,比如可以使用vercel进行部署,不过由于时间关系,部署教程和一键部署会在后续完善。

### How To Use | 如何使用

使用post通过 `域名` + `/translate` + `json请求体` 这样的形式获取json响应。

请求示例:

``` bash
curl --location --request POST 'https://YOUR-DOMAIN/api/translate' \
--header 'Content-Type: application/json' \
--data-raw '{
"text": "Hello, World!",
"source_lang": "en",
"target_lang": "de"
}'
```
直接复制到命令行测试:

<details>
<summary>点击展开</summary>

``` bash
curl --location 'https://YOUR-DOMAIN/translate' --header 'Content-Type: application/json' --data '{"text": "你好,世界", "source_lang": "zh", "target_lang": "en"}'
```
</details>

响应示例:

``` json
{
"code": 200,
"message": "success",
"data": "Hello, world.",
"source_lang": "zh",
"target_lang": "en",
"alternatives": ["Hello, World.", "Hello, world!", "Hi, world."]
}
```

请修改`YOUR-DOMAIN`为你部署服务的域名,建议搭配浏览器插件沉浸式翻译一同使用。

#### 沉浸式翻译设置

1. 在浏览器上安装最新的 [沉浸式翻译](https://github.com/immersive-translate/immersive-translate/releases)
2. 点击左下角的 "开发者设置"。启用测试版实验功能。
3. 翻译服务选中 `DeepLX(beta)`
3. 设置 URL 为刚才获取的访问路径(需带translate)。

![沉浸式翻译](https://github.com/LegendLeo/deeplx-serverless/assets/25115173/d3affe2b-9e99-4d5c-bc8c-cd67e70d0368)

## 自托管

尽管本项目是专为 serverless 适配的方案,但是也能使用自己提供服务器进行部署

``` bash
git clone https://github.com/guobao/deeplx-serverless
cd deeplx-serverless
npm install
npm run start
```

## 鸣谢
1. [OwO-Network/DeepLX](https://github.com/OwO-Network/DeepLX)
2. [LegendLeo/deeplx-serverless](https://github.com/LegendLeo/deeplx-serverless)
3. [bropines/Deeplx-vercel](https://github.com/bropines/Deeplx-vercel)
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = (req, res) => {
res.json({
code: 200,
message: "Welcome to the DeepL Free API. Please POST to /translate. Visit http://github.com/OwO-Network/DeepLX for more information."
});
};
24 changes: 24 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "deeplx-serverless",
"version": "1.0.0",
"description": "DeepLX Free API for serverless",
"main": "translate.js",
"scripts": {
"start": "node server.js",
"test": "node test.js"
},
"keywords": [
"deeplx",
"deepl",
"translate",
"serverless"
],
"license": "MIT",
"dependencies": {
"axios": "^1.6.3",
"body-parser": "^1.20.2",
"express": "^4.18.2",
"lodash": "^4.17.21",
"random-int": "^3.0.0"
}
}
33 changes: 33 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const express = require('express');
const bodyParser = require('body-parser');
const { translate } = require('./translate');

const app = express();
const PORT = 9000;

app.use(bodyParser.json());

app.post('/translate', async (req, res) => {
const { text, source_lang, target_lang } = req.body;

try {
const result = await translate(text, source_lang, target_lang);
const responseData = {
alternatives: result.alternatives,
code: 200,
data: result.text, // 取第一个翻译结果
id: Math.floor(Math.random() * 10000000000), // 生成一个随机 ID
method: 'Free',
source_lang,
target_lang,
};

res.json(responseData);
} catch (error) {
res.status(500).json({ error: 'Translation failed' });
}
});

app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
15 changes: 15 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const translate = require('./translate');

;(async () => {
// Example Call
console.log(await translate('你好,我是练习时长两年半的个人练习生', 'ZH', 'EN', true, true));
console.log(
await translate(
'Generate a cryptographically strong random string',
'EN',
'ZH',
true,
true
)
);
})()
97 changes: 97 additions & 0 deletions translate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
const axios = require('axios').default;
const { random } = require('lodash');

const DEEPL_BASE_URL = 'https://www2.deepl.com/jsonrpc';
const headers = {
'Content-Type': 'application/json',
Accept: '*/*',
'x-app-os-name': 'iOS',
'x-app-os-version': '16.3.0',
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate, br',
'x-app-device': 'iPhone13,2',
'User-Agent': 'DeepL-iOS/2.9.1 iOS 16.3.0 (iPhone13,2)',
'x-app-build': '510265',
'x-app-version': '2.9.1',
Connection: 'keep-alive',
};

function getICount(translateText) {
return (translateText || '').split('i').length - 1;
}

function getRandomNumber() {
return random(8300000, 8399998) * 1000;
}

function getTimestamp(iCount) {
const ts = Date.now();
if (iCount === 0) {
return ts;
}
iCount++;
return ts - (ts % iCount) + iCount;
}

async function translate(
text,
sourceLang = 'AUTO',
targetLang = 'ZH',
numberAlternative = 0,
printResult = false,
) {
const iCount = getICount(text);
const id = getRandomNumber();

numberAlternative = Math.max(Math.min(3, numberAlternative), 0);

const postData = {
jsonrpc: '2.0',
method: 'LMT_handle_texts',
id: id,
params: {
texts: [{ text: text, requestAlternatives: numberAlternative }],
splitting: 'newlines',
lang: {
source_lang_user_selected: sourceLang.toUpperCase(),
target_lang: targetLang.toUpperCase(),
},
timestamp: getTimestamp(iCount),
},
};

let postDataStr = JSON.stringify(postData);

if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
postDataStr = postDataStr.replace('"method":"', '"method" : "');
} else {
postDataStr = postDataStr.replace('"method":"', '"method": "');
}

try {
const response = await axios.post(DEEPL_BASE_URL, postDataStr, {
headers: headers,
});

if (response.status === 429) {
throw new Error(
`Too many requests, your IP has been blocked by DeepL temporarily, please don't request it frequently in a short time.`
);
}

if (response.status !== 200) {
console.error('Error', response.status);
return;
}

const result = response.data.result.texts[0]
if (printResult) {
console.log(result);
}
return result;
} catch (err) {
console.error(err);
}
}

exports.translate = translate;
5 changes: 5 additions & 0 deletions vercel.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rewrites": [
{ "source": "/", "destination": "/index.js" }
]
}

0 comments on commit b6c1f9d

Please sign in to comment.