Merge pull request #231 from Bush2021/fix-google-translate

fix: update API for Google Translate
This commit is contained in:
Gabe
2025-05-09 14:08:16 +08:00
committed by GitHub
3 changed files with 23 additions and 22 deletions

View File

@@ -255,10 +255,19 @@ export const apiTranslate = async ({
);
switch (translator) {
case OPT_TRANS_GOOGLE:
trText = res.sentences.map((item) => item.trans).join(" ");
isSame = to === res.src;
case OPT_TRANS_GOOGLE: {
if (!res || !Array.isArray(res) || res.length < 2) {
console.error("Unexpected response structure:", res);
trText = "Error: Invalid response structure";
isSame = false;
} else {
const translatedText = Array.isArray(res[0]) ? res[0].join(" ") : "Translation unavailable";
const isTranslationComplete = to === (Array.isArray(res[1]) ? res[1][0] : undefined);
trText = translatedText;
isSame = isTranslationComplete;
}
break;
}
case OPT_TRANS_MICROSOFT:
trText = res
.map((item) => item.translations.map((item) => item.text).join(" "))

View File

@@ -58,26 +58,16 @@ const keyPick = (translator, key = "", cacheMap) => {
};
const genGoogle = ({ text, from, to, url, key }) => {
const params = {
client: "gtx",
dt: "t",
dj: 1,
ie: "UTF-8",
sl: from,
tl: to,
q: text,
};
const input = `${url}?${queryString.stringify(params)}`;
const body = JSON.stringify([[ [text], from, to ], "wt_lib"]);
const init = {
method: "POST",
headers: {
"Content-type": "application/json",
"Content-Type": "application/json+protobuf",
"X-Goog-API-Key": key,
},
body,
};
if (key) {
init.headers.Authorization = `Bearer ${key}`;
}
return [input, init];
return [url, init];
};
const genMicrosoft = async ({ text, from, to }) => {

View File

@@ -87,8 +87,10 @@ export const URL_MICROSOFT_AUTH = "https://edge.microsoft.com/translate/auth";
export const URL_MICROSOFT_LANGDETECT =
"https://api-edge.cognitive.microsofttranslator.com/detect?api-version=3.0";
export const URL_GOOGLE_TRAN =
"https://translate.googleapis.com/translate_a/single";
export const URL_GOOGLE_TRAN = "https://translate-pa.googleapis.com/v1/translateHtml";
export const DEFAULT_GOOGLE_API_KEY = "AIzaSyATBXajvzQLTDHEQbcpq0Ihe0vWDHmO520";
export const URL_BAIDU_LANGDETECT = "https://fanyi.baidu.com/langdetect";
export const URL_BAIDU_SUGGEST = "https://fanyi.baidu.com/sug";
export const URL_BAIDU_TTS = "https://fanyi.baidu.com/gettts";
@@ -547,7 +549,7 @@ const defaultOllamaApi = {
export const DEFAULT_TRANS_APIS = {
[OPT_TRANS_GOOGLE]: {
url: URL_GOOGLE_TRAN,
key: "",
key: DEFAULT_GOOGLE_API_KEY,
fetchLimit: DEFAULT_FETCH_LIMIT, // 最大任务数量
fetchInterval: DEFAULT_FETCH_INTERVAL, // 任务间隔时间
},