feat: add baidu translate

This commit is contained in:
zyronon
2023-09-11 14:19:04 +08:00
parent 00a479a726
commit a66b32578d
7 changed files with 65 additions and 54 deletions

36
src/hooks/translate.ts Normal file
View File

@@ -0,0 +1,36 @@
import {Article} from "@/types.ts";
import Baidu from "@opentranslate/baidu";
import {axiosInstance} from "@/utils/http.ts";
import useSleep from "@/hooks/useSleep.ts";
import {CnKeyboardMap, useSplitCNArticle} from "@/hooks/useSplitArticle.ts";
export async function useArticleTranslate(article: Article) {
const baidu = new Baidu({
axios: axiosInstance,
config: {
appid: "20230910001811857",
key: "Xxe_yftQR3K3Ue43NQMC"
}
})
let articleTranslate
// if (article.translate) {
if (false) {
articleTranslate = useSplitCNArticle(article.translate, 'cn', CnKeyboardMap)
}
for (let i = 0; i < article.sections.length; i++) {
let v = article.sections[i]
for (let j = 0; j < v.length; j++) {
let sentence = v[j]
if (articleTranslate) {
sentence.translate = articleTranslate[i][j].sentence
} else {
await useSleep(500)
let r = await baidu.translate(sentence.sentence, 'en', 'zh-CN')
console.log('r', r)
sentence.translate = r.trans.paragraphs[0]
}
}
}
}

5
src/hooks/useSleep.ts Normal file
View File

@@ -0,0 +1,5 @@
export default async function (time: number) {
return new Promise(resolve => {
setTimeout(resolve, time)
})
}