-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
86 lines (85 loc) · 2.54 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
exports.translate = async (text, { key, file }) => {
return new Promise((resolve) => {
const payload = JSON.stringify({
model: 'Qwen/Qwen2.5-72B-Instruct',
messages: [
{
role: 'system',
content: [
{
type: 'text',
text: 'You are a professional, authentic machine translation engine.',
},
],
},
{
role: 'user',
content: [
{
type: 'text',
text: `Translate the following source text to chinese: ${text},Output translation directly without any additional text. Remember, Keep ALL HTML TAG AND ATTRIBUTE, ONLY TRANSLATE CONTENT!`,
},
],
},
],
temperature: 0,
top_p: 0.95,
max_tokens: 4096,
});
const apiKey = process.env.OPENAI_API_KEY;
const url = process.env.OPENAI_URL;
const res = spawn('curl', [
'--request',
'POST',
'--url',
url,
'-H',
'Content-Type: application/json',
'-H',
`Authorization: Bearer ${apiKey}`,
'-d',
payload,
]);
let result = '';
res.stdout.on('data', (data) => {
result += data.toString();
});
res.stdout.on('close', () => {
try {
const json = JSON.parse(result);
const translate = json.choices?.[0]?.message?.content;
if (!translate) {
console.error(`ai 翻译失败: [${text}] -> [${result}]`);
// Note: 创建一个 error.txt ,如果不存在则创建
const errorPath = path.resolve(__dirname, 'error.txt');
if (!fs.existsSync(errorPath)) {
fs.writeFileSync(errorPath, '');
}
// Note:追加到文件
fs.appendFileSync(
errorPath,
`[${file}-${key}]: ${text} -> ${result}\n`
);
resolve('【翻译引擎出错,请联系作者】');
return;
}
resolve(translate);
} catch (e) {
console.error(`ai 翻译失败: [${text}] -> [${result}]`);
// Note: 创建一个 error.txt ,如果不存在则创建
if (!fs.existsSync('error.txt')) {
fs.writeFileSync('error.txt', '');
}
// Note:追加到文件
fs.appendFileSync(
'error.txt',
`[${file}-${key}]: ${text} -> ${result}\n`
);
resolve('【翻译引擎出错,请联系作者】');
}
});
});
};