Skip to content

Commit

Permalink
chore: optimize AI translation logic
Browse files Browse the repository at this point in the history
Update Translate.response.dev.js
Update Translate.mjs
  • Loading branch information
adolphnov authored and VirgilClyne committed Jan 16, 2025
1 parent 56293a0 commit fdcdb67
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 11 deletions.
3 changes: 3 additions & 0 deletions src/Translate.response.dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,9 @@ async function Translator(vendor = "Google", method = "Part", text = [], [source
case "DeepLX":
length = 20;
break;
case "AI":
length = 25;
break;
}
let Translation = [];
switch (method) {
Expand Down
29 changes: 18 additions & 11 deletions src/class/Translate.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ export default class Translate {
"User-Agent": "DualSubs",
"Content-Type": "application/json; charset=utf-8",
};
request.body = {
request.body = JSON.stringify({
q: text,
from: source,
to: target,
Expand All @@ -436,7 +436,7 @@ export default class Translate {
signType: "v3",
sign: "",
curtime: Math.floor(+new Date() / 1000),
};
});
return await fetch(request)
.then(response => {
const body = JSON.parse(response.body);
Expand All @@ -447,32 +447,39 @@ export default class Translate {

async AI(text = [], source = this.Source, target = this.Target, api = this.API) {
text = Array.isArray(text) ? text : [text];
const dataParseReg = /-\s*id:\s\d+\s*text:\s([^\n]*)/g;
source = this.#LanguagesCode.Google[source] ?? this.#LanguagesCode.Google[source?.split?.(/[-_]/)?.[0]];
target = this.#LanguagesCode.Google[target] ?? this.#LanguagesCode.Google[target?.split?.(/[-_]/)?.[0]];
const request = {};
request.url = `${api.BaseURL}/v1/chat/completions`;
// 完整请求url 以兼容不同api
request.url = api.URL;
request.headers = {
"User-Agent": "DualSubs",
"Content-Type": "application/json; charset=utf-8",
...(api.Token && { Authorization: `Bearer ${api.Token}` }),
};
request.body = {
const yamlPrompt = text.map((t, i) => `\n- id: ${i + 1}\n text: ${t}\n`).join("");
const prompt = `${api.Prompt}\n{{summary_prompt}}{{terms_prompt}} You will be given a YAML formatted video/episode subtitles containing entries with \"id\" and \"text\" fields. Here is the input:\n\n<yaml>${yamlPrompt}</yaml>\n\nFor each entry in the YAML, translate the contents of the "text" field into language: ${target}, Write the translation back into the "text" field for that entry. Please translate the complete sentences first, and then breaking it down into multiple fragments based on the content and the id length in a freer, more conversational style.\n\nHere is an example of the expected format:\n\n<example>\nInput:\n - id: 1\n text: In China, if you want\n - id: 2\n text: noodles\n - id: 3\n text: come to Shaanxi!\nOutput:\n - id: 1\n text: 在中国,如果你想\n - id: 2\n text: 吃面\n - id: 3\n text: 来陕西!\n</example>\n\nPlease return the translated YAML directly without wrapping <yaml> tag or include any additional information.`;

request.body = JSON.stringify({
model: api.Model,
temperature: 1,
stream: false, // 可选stream或一次返回
messages: [
{
role: "system",
content: api.Prompt,
},
{
role: "user",
content: text.join("\n"),
content: prompt,
},
],
};
});

return await fetch(request)
.then(response => {
const body = JSON.parse(response.body);
return body?.choices?.[0]?.message?.content?.split("\n") ?? `翻译失败, vendor: ${"AI"}`;
const content = body?.choices?.[0]?.message?.content ?? "";
const data = [...content.matchAll(dataParseReg)].map(i => i[1]);
// console.log(`text_length ${text.length}, trans_length ${data.length}`);
return data.length ? data : [`翻译失败, vendor: ${"AI"}`];
})
.catch(error => Promise.reject(error));
}
Expand Down

0 comments on commit fdcdb67

Please sign in to comment.