Skip to content

Commit

Permalink
国际化 ai翻译
Browse files Browse the repository at this point in the history
  • Loading branch information
xushengfeng committed Sep 9, 2024
1 parent 691b568 commit 15385d4
Showing 1 changed file with 77 additions and 1 deletion.
78 changes: 77 additions & 1 deletion lib/translate/tool.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const enableEn = args.includes("-e");
const inputFile = args.includes("-i") ? args[args.indexOf("-i") + 1] : "";
const uuid = args.includes("-u");
const pure = args.includes("-p");
const ai = args.includes("--ai") ? args[args.indexOf("--ai") + 1] : "";

const source = require(path.join(rootDir, "./source.json"));

Expand All @@ -33,7 +34,10 @@ const srcCommit = {
"zh-HANT": { id: "eff1861", finishId: [] }, // 繁体中文
};

if (lang) {
/**
* @param {string} lang
*/
function getToTranslate(lang) {
let l = {};
try {
l = require(path.join(rootDir, `./${lang}.json`));
Expand All @@ -52,6 +56,7 @@ if (lang) {
} catch (error) {}

const t = [];
const tt = [];

const w = args.includes("-a");

Expand All @@ -62,6 +67,7 @@ if (lang) {
t.push(
`"${source[i]}","${i}","${enLan[source[i]] || ""}","${pure ? "" : l[source[i]] || ""}"`,
);
tt.push(i);
}

if (!w) {
Expand Down Expand Up @@ -94,6 +100,11 @@ if (lang) {
fs.writeFileSync(csvFilePath, csv);

console.log(csvFilePath);
return tt;
}

if (lang) {
getToTranslate(lang);
}

if (inputFile) {
Expand Down Expand Up @@ -130,3 +141,68 @@ if (uuid) {
}
fs.writeFileSync("source.json", `${JSON.stringify(source, null, 4)}\n`);
}

if (ai) {
const tt = getToTranslate(ai);
console.log(tt);
fetch("https://api.chatanywhere.tech/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.gpt}`,
},
body: JSON.stringify({
model: "gpt-4o-mini",
stream: false,
messages: [
{
role: "system",
content: "你将翻译提供的JSON,不需要任何解释",
},
{
role: "user",
content: `把下面这些JSON翻译成 en\n${JSON.stringify(["hello", "bye"])}`,
},
{
role: "assistant",
content: `${JSON.stringify(["你好", "再见"])}`,
},
{
role: "user",
content: `把下面这些JSON翻译成 ${ai}\n${JSON.stringify(tt)}`,
},
],
}),
})
.then((res) => res.json())
.then((data) => {
console.log(data.choices[0].message);
const x = JSON.parse(data.choices[0].message.content);
const v = {};
for (const i in x) {
const zh = tt[i];
if (!source[zh]) {
console.log(`no ${zh}`);
continue;
}
v[source[zh]] = x[i];
}

let l = {};
try {
l = require(path.join(rootDir, `./${ai}.json`));
} catch (error) {
console.log("\x1B[32m%s\x1B[0m", `+ ${ai}`);
}

const out = {};
for (const i in source) {
const id = source[i];
out[id] = v[id] || l[id] || "";
}
fs.writeFileSync(
`${ai}.json`,
`${JSON.stringify(out, null, 4)}\n`,
);
});
}

0 comments on commit 15385d4

Please sign in to comment.