introduce prompt translation (yandex translate)

This commit is contained in:
Timofey Gelazoniya 2023-11-27 16:31:44 +03:00
parent e3cb75e152
commit 3a67c0ce65
Signed by: zeldon
GPG Key ID: 047886915281DD2A
4 changed files with 75 additions and 3 deletions

3
package-lock.json generated
View File

@ -1,9 +1,10 @@
{
"name": "fooocos3",
"name": "fooocos-telegram-bot",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "fooocos-telegram-bot",
"dependencies": {
"@grammyjs/runner": "^2.0.3",
"@grammyjs/transformer-throttler": "^1.2.1",

View File

@ -30,4 +30,4 @@
"pino": "^8.16.2",
"pino-pretty": "^10.2.3"
}
}
}

View File

@ -1,5 +1,6 @@
import { logger } from "#root/logger.js";
import { predict } from "#root/predict.js";
import { Language, translate } from "#root/translate.js";
import { downloadImage, isFooocosAlive, uploadPhoto } from "#root/utils.js";
import { apiThrottler } from "@grammyjs/transformer-throttler";
import { Bot, Context, InlineKeyboard, InlineQueryResultBuilder, InputMediaBuilder } from "grammy";
@ -56,7 +57,18 @@ async function handleChosenInlineResult(ctx: Context) {
activeTasks.set(userId, true);
const gen = predict(prompt);
let translatedPrompt;
try {
translatedPrompt = await translate(prompt, Language.en, Language.auto);
} catch (err) {
logger.warn(err, "prompt translation error");
translatedPrompt = prompt;
}
logger.trace({ prompt, translatedPrompt });
const gen = predict(translatedPrompt);
for await (const state of gen) {
if (state.status === "RUNNING") {

59
src/translate.ts Normal file
View File

@ -0,0 +1,59 @@
import { randomUUID } from 'crypto';
// https://yandex.com/dev/translate/doc/en/concepts/api-overview
export enum Language {
auto = '',
zh_cn = 'zh',
zh_tw = 'zh',
en = 'en',
ja = 'ja',
ko = 'ko',
fr = 'fr',
es = 'es',
ru = 'ru',
de = 'de',
it = 'it',
tr = 'tr',
pt_pt = 'pt',
pt_br = 'pt',
vi = 'vi',
id = 'id',
th = 'th',
ms = 'ms',
ar = 'ar',
hi = 'hi',
nb_no = 'no',
nn_no = 'no',
fa = 'fa',
}
export async function translate(text: string, to: Language, from: Language) {
const url = 'https://translate.yandex.net/api/v1/tr.json/translate';
const query = new URLSearchParams({
id: randomUUID().replaceAll('-', '') + '-0-0',
srv: 'android',
});
const res = await fetch(`${url}?${query}`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
source_lang: from,
target_lang: to,
text
}),
});
if (res.ok) {
const result = await res.json();
if (result.text) {
return result.text[0];
} else {
throw JSON.stringify(result);
}
} else {
throw `Http Request Error\nHttp Status: ${res.status}\n${await res.text()}`;
}
}