node脚本 实现博客文件md翻译
后续试试实现学院就业推文更新
openai国际化翻译
代码
const { OpenAI } = require("openai");
const { HttpsProxyAgent } = require("https-proxy-agent")
const { i18n } = require('../../next-i18next.config') // 直接数组枚举也行
const fs = require('fs');
const path = require('path');
const myApiKey = "自己的key"
const proxyUrl = "http://127.0.0.1:7890" // 这里用cfw的端口号,需要自己先有魔法
const mdxFolderPath = path.resolve(__dirname, '../../pages'); // 需要翻译的文件夹路径 以mdx文章为例
const files = fs.readdirSync(mdxFolderPath); //读取指定文件夹下的所有文件
const openai = new OpenAI({
apiKey: myApiKey,
httpAgent: new HttpsProxyAgent(proxyUrl)
});
const openai = new OpenAI({
apiKey: myApiKey,
httpAgent: new HttpsProxyAgent(proxyUrl)
});
const requestChatgpt = async (role, prompt1, prompt2)=>{
const completion = await openai.chat.completions.create({
model: "gpt-4o", // 高性价
messages: [
{ role: "system", content: role },
{
role: "user",
content: prompt1,
},
{
role: "user",
content: prompt2,
},
],
});
return completion.choices[0].message.content
}
const translateMDX = async()=> {
//角色设定
const role = "You are a translator who is familiar with front-end development and markdown. Only give me the text output";
//提示词后缀
const prompt_suf = "注意:请在mdx锚点需要根据当前页面的真实路径, 其中language为当前翻译的语言。";
const mdxFiles = files.filter(item=> item.endsWith('.mdx')); //筛选出的mdx文件
for (const fileName of mdxFiles.filter(fname => fname.endsWith('.en.mdx'))) {
const filePath = path.resolve(mdxFolderPath, fileName)
// 读取文件内容
const prompt_content = fs.readFileSync(filePath, 'utf-8')
for (const locale of i18n.locales) {
//要生成的文件名
const newFileName = fileName.replace('.en', `.${locale}`);
if( mdxFiles.includes(newFileName))continue; //如果想翻译的文件已经存在 ,则跳过
//要生成的文件路径
const newFilePath = path.resolve(mdxFolderPath, newFileName)
// 组成提示词 prompt
const prompt_pre = `Please translate the content in mdx format into "${locale}" language`;
const prompt = prompt_pre + prompt_suf;
// 调用ai翻译
try {
let result = await requestChatgpt(role, prompt, prompt_content);
// const result = prompt_content; //copy文件用
result = result.replace('```mdx', '').replace('```', '');
fs.writeFileSync(newFilePath, result);
console.log(newFileName + "已翻译完成!")
} catch(err) {
console.log(fileName + "翻译失败!")
}
}
}
}
写于2024年9月5日 By 芒果🥭