feat: Invoke translateNote via API.

This commit is contained in:
Caspian
2023-12-01 17:53:49 +00:00
parent f520e63b19
commit e7409a4e7a
8 changed files with 285 additions and 229 deletions
+4 -206
View File
@@ -1,20 +1,14 @@
import AsyncLock from "async-lock"
import {
AnalyzeDocumentChain,
LLMChain,
loadSummarizationChain,
} from "langchain/chains"
import { AnalyzeDocumentChain, loadSummarizationChain } from "langchain/chains"
import { OpenAI } from "langchain/llms/openai"
import { PromptTemplate } from "langchain/prompts"
import { getLocale } from "next-intl/server"
import removeMarkdown from "remove-markdown"
import { Metadata } from "@prisma/client"
import { QueryClient } from "@tanstack/react-query"
import { defaultLocale, languageNames, locales } from "~/i18n"
import { toCid, toGateway } from "~/lib/ipfs-parser"
import { llmModelSwitcherByTextLength } from "~/lib/llm-model-switcher-by-text-length"
import { defaultLocale, locales } from "~/i18n"
import { toGateway } from "~/lib/ipfs-parser"
import prisma from "~/lib/prisma.server"
import { cacheGet } from "~/lib/redis.server"
import { Language } from "~/lib/types"
@@ -38,6 +32,7 @@ export const fetchGetPage = async (
useStat: input.useStat,
noteId: input.noteId,
handle: input.handle,
translateTo: input.translateTo,
}),
}) as Promise<ReturnType<typeof pageModel.getPage>>
})
@@ -77,203 +72,6 @@ export const fetchGetPagesBySite = async (
})
}
// Content translation
type ContentTranslation = {
title?: string
content?: string
}
let translationModel4K: OpenAI | undefined
let translationModel16K: OpenAI | undefined
if (process.env.OPENAI_API_KEY) {
const options = {
openAIApiKey: process.env.OPENAI_API_KEY,
temperature: 0.2,
maxTokens: -1,
}
translationModel4K = new OpenAI({ ...options, modelName: "gpt-3.5-turbo" })
translationModel16K = new OpenAI({
...options,
modelName: "gpt-3.5-turbo-16k",
})
}
type ChainKeyType = `${4 | 16}k_${Language}` // e.g. "4k_en" | "4k_zh" | "4k_zh-TW" | "4k_ja" | "16k_en" | "16k_zh" | "16k_zh-TW" | "16k_ja"
const translationChains = new Map<ChainKeyType, LLMChain>()
const getOriginalTranslation = async (
cid: string,
targetLang: Language,
originalLang?: Language,
): Promise<ContentTranslation | undefined> => {
if (!translationModel4K || !translationModel16K) return
try {
const { title, content } = await (
await fetch(toGateway(`ipfs://${cid}`))
).json()
// If the detected language is the same as the target language, return the original content
if (originalLang === targetLang) {
console.warn(
`|__ Warn: Detected language is the same as the target language, return the original content: ${cid}, ${targetLang}`,
)
return
}
console.time(`fetching translation ${cid}, ${targetLang}`)
const { modelSize, tokens } = llmModelSwitcherByTextLength(content, {
includeResponse: { lang: targetLang },
})
if (!modelSize) {
console.error(
`|__ Error: Content too long for translation: ${cid}, ${targetLang}. (Tokens: ${tokens})`,
)
return
}
let chain = translationChains.get(`${modelSize}_${targetLang}`)
if (!chain) {
const prompt = new PromptTemplate({
template: `Translate the following text into "${languageNames[targetLang]}" language:
{text}
Translation:`,
inputVariables: ["text"],
})
const translateModel =
modelSize === "4k" ? translationModel4K : translationModel16K
chain = new LLMChain({ llm: translateModel, prompt })
translationChains.set(`${modelSize}_${targetLang}`, chain)
}
const t = await chain.call({ text: title })
const c = await chain.call({ text: content })
console.timeEnd(`fetching translation ${cid}, ${targetLang}`)
return {
title: t.text,
content: c.text,
}
} catch (error) {
console.error(error)
console.timeEnd(`fetching translation ${cid}, ${targetLang}`)
}
}
async function getTranslation({
cid,
lang = "en",
}: {
cid: string
lang?: Language
}) {
const translatedContent = (await cacheGet({
key: ["translation", cid, lang],
allowEmpty: true,
noUpdate: true,
noExpire: true,
getValueFun: async () => {
let result
await lock.acquire(`translation_${cid}`, async () => {
const meta = await prisma.metadata.findFirst({
where: {
uri: `ipfs://${cid}`,
},
})
const key = "ai_translation"
const translations = meta?.[key as keyof Metadata] as Record<
string,
ContentTranslation
>
const translatedJson = translations?.[lang]
if (translatedJson) {
result = translatedJson
} else {
const newTranslation = await getOriginalTranslation(cid, lang)
if (newTranslation) {
/**
* e.g.
*
* {
* "en": {
* "title": "title",
* "content": "content"
* },
* "zh": {
* "title": "标题",
* "content": "内容"
* },
* ...
* }
*
*/
const finalTranslation = {
...translations,
[lang]: newTranslation,
}
if (meta) {
await prisma.metadata.update({
where: { uri: `ipfs://${cid}` },
data: {
[key as keyof Metadata]: finalTranslation,
},
})
} else {
await prisma.metadata.create({
data: {
uri: `ipfs://${cid}`,
[key as keyof Metadata]: finalTranslation,
},
})
}
result = newTranslation
}
}
})
return result
},
})) as ContentTranslation | undefined
return translatedContent
}
// Modify page content with translation
export async function decoratePageWithTranslation(
page?: Awaited<ReturnType<typeof pageModel.getPage>> | null,
) {
if (!page) return
const cid = toCid(page?.metadata?.uri || "")
const targetLanguage = (await getLocale()) as Language
const originalLanguage = page?.metadata?.content?.originalLanguage
if (originalLanguage === targetLanguage) {
return
}
const translatedContent = await getTranslation({
cid,
lang: targetLanguage,
})
if (translatedContent && page?.metadata?.content) {
page.metadata.content["content"] = translatedContent.content
page.metadata.content["title"] = translatedContent.title
}
}
// Post summary
let model: OpenAI | undefined