Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
mololab
GitHub Repository: mololab/json-translator
Path: blob/master/src/modules/functions.ts
235 views
1
import { translate } from '@vitalets/google-translate-api';
2
import * as bingTranslator from 'bing-translate-api';
3
import createHttpProxyAgent from 'http-proxy-agent';
4
import axios from 'axios';
5
import { getLanguageKeyFromValue, safeValueTransition } from './helpers';
6
import { warn } from '../utils/console';
7
import translate2 from '@iamtraction/google-translate';
8
import OpenAI from 'openai';
9
import { GTPTranslateLanguages } from './languages';
10
11
export async function translateWithLibre(
12
str: string,
13
from: string,
14
to: string
15
): Promise<string> {
16
let body = {
17
q: safeValueTransition(str),
18
source: from,
19
target: to,
20
format: 'text',
21
api_key: '',
22
secret: 'YK4VRVW',
23
};
24
25
const { data } = await axios.post(
26
'https://libretranslate.com/translate',
27
body,
28
{
29
headers: {
30
Origin: 'https://libretranslate.com',
31
},
32
}
33
);
34
35
return data.translatedText;
36
}
37
38
export async function translateWithArgos(
39
str: string,
40
from: string,
41
to: string
42
): Promise<string> {
43
let body = {
44
q: safeValueTransition(str),
45
source: from,
46
target: to,
47
};
48
49
const { data } = await axios.post(
50
'https://translate.argosopentech.com/translate',
51
body,
52
{
53
headers: {
54
Origin: 'https://translate.argosopentech.com',
55
Referer: 'https://translate.argosopentech.com',
56
},
57
}
58
);
59
60
return data.translatedText;
61
}
62
63
export async function translateWithBing(
64
str: string,
65
from: string,
66
to: string
67
): Promise<string> {
68
const { translation } = await bingTranslator.translate(
69
safeValueTransition(str),
70
from,
71
to,
72
false
73
);
74
75
return translation;
76
}
77
78
export async function translateWithGoogle(
79
str: string,
80
from: string,
81
to: string
82
): Promise<string> {
83
// step: if proxy list provided
84
if (
85
global.proxyList &&
86
global.proxyList.length > 0 &&
87
global.proxyIndex !== -1
88
) {
89
let proxy = global.proxyList[global.proxyIndex];
90
91
// step: new proxy exist
92
if (proxy) {
93
let agent = createHttpProxyAgent(`http://${proxy}`);
94
95
let translatedStr = await translateWithGoogleByProxySupport(
96
str,
97
from,
98
to,
99
{
100
agent,
101
timeout: 4000,
102
}
103
);
104
105
return translatedStr;
106
} else {
107
warn('No new proxy exists, continuing without proxy');
108
global.proxyIndex = -1;
109
110
let translatedStr = await translateWithGoogleByProxySupport(
111
str,
112
from,
113
to
114
);
115
116
return translatedStr;
117
}
118
} else {
119
// step: translate without proxy
120
let translatedStr = await translateWithGoogleByProxySupport(str, from, to);
121
122
return translatedStr;
123
}
124
}
125
126
async function translateWithGoogleByProxySupport(
127
str: string,
128
from: string,
129
to: string,
130
options?: { agent: any; timeout: number }
131
) {
132
const { text } = await translate(safeValueTransition(str), {
133
from: from,
134
to: to,
135
fetchOptions: { agent: options !== undefined ? options.agent : undefined },
136
});
137
138
return text;
139
}
140
141
export async function translateWithDeepL(
142
str: string,
143
from: string,
144
to: string
145
): Promise<string> {
146
const DEEPL_API_KEY = process.env.DEEPL_API_KEY;
147
const DEEPL_API_URL = process.env.DEEPL_API_URL || 'api-free.deepl.com';
148
if (!DEEPL_API_KEY) {
149
warn('process.env.DEEPL_API_KEY is not defined');
150
}
151
if (!process.env.DEEPL_API_URL) {
152
warn(
153
'process.env.DEEPL_API_URL is not defined, using api-free.deepl.com as default'
154
);
155
}
156
157
const body = {
158
text: [safeValueTransition(str)],
159
target_lang: to,
160
source_lang: from,
161
};
162
163
const { data } = await axios.post(
164
`https://${DEEPL_API_URL}/v2/translate`,
165
body,
166
{
167
headers: {
168
Authorization: `DeepL-Auth-Key ${DEEPL_API_KEY}`,
169
'Content-Type': 'application/json',
170
},
171
}
172
);
173
174
return data.translations[0].text;
175
}
176
177
export async function translateWithGoogle2(
178
str: string,
179
from: string,
180
to: string
181
) {
182
const response = await translate2(str, { from: from, to: to });
183
184
return response.text;
185
}
186
187
export async function translateWithGPT35Turbo(
188
str: string,
189
from: string,
190
to: string
191
) {
192
return translateWithGPT('gpt-3.5-turbo', str, from, to);
193
}
194
195
export async function translateWithGPT4(str: string, from: string, to: string) {
196
return translateWithGPT('gpt-4', str, from, to);
197
}
198
199
export async function translateWithGPT4o(
200
str: string,
201
from: string,
202
to: string
203
) {
204
return translateWithGPT('gpt-4o', str, from, to);
205
}
206
207
export async function translateWithGPT4oMini(
208
str: string,
209
from: string,
210
to: string
211
) {
212
return translateWithGPT('gpt-4o-mini', str, from, to);
213
}
214
215
export async function translateWithGPT5(
216
str: string,
217
from: string,
218
to: string
219
) {
220
return translateWithGPT('gpt-5', str, from, to);
221
}
222
223
export async function translateWithGPT5Nano(
224
str: string,
225
from: string,
226
to: string
227
) {
228
return translateWithGPT('gpt-5-nano-2025-08-07', str, from, to);
229
}
230
231
export async function translateWithGPT5Mini(
232
str: string,
233
from: string,
234
to: string
235
) {
236
return translateWithGPT('gpt-5-mini-2025-08-07', str, from, to);
237
}
238
239
export async function translateWithGPT(
240
model: string,
241
str: string,
242
from: string,
243
to: string
244
) {
245
return translateWithLLM(model, str, from, to, 'openai');
246
}
247
248
export async function translateWithGemma7B(
249
str: string,
250
from: string,
251
to: string
252
) {
253
return translateWithGroq('gemma-7b-it', str, from, to);
254
}
255
256
export async function translateWithGemma9B(
257
str: string,
258
from: string,
259
to: string
260
) {
261
return translateWithGroq('gemma2-9b-it', str, from, to);
262
}
263
264
export async function translateWithMixtral8x7B(
265
str: string,
266
from: string,
267
to: string
268
) {
269
return translateWithGroq('mixtral-8x7b-32768', str, from, to);
270
}
271
272
export async function translateWithLlama8B(
273
str: string,
274
from: string,
275
to: string
276
) {
277
return translateWithGroq('llama3-8b-8192', str, from, to);
278
}
279
280
export async function translateWithLlama70B(
281
str: string,
282
from: string,
283
to: string
284
) {
285
return translateWithGroq('llama3-70b-8192', str, from, to);
286
}
287
288
export async function translateWithGroq(
289
model: string,
290
str: string,
291
from: string,
292
to: string
293
) {
294
return translateWithLLM(model, str, from, to, 'groq');
295
}
296
297
export async function translateWithLlamaCpp(
298
str: string,
299
from: string,
300
to: string
301
) {
302
return translateWithLLM('', str, from, to, 'llama-cpp');
303
}
304
305
export async function translateWithLLM(
306
model: string,
307
str: string,
308
from: string,
309
to: string,
310
provider: 'openai' | 'groq' | 'llama-cpp'
311
) {
312
type ChatCompletionRequestMessage = {
313
role: 'system' | 'user' | 'assistant';
314
content: string;
315
};
316
317
let fromKey = getLanguageKeyFromValue(from, GTPTranslateLanguages);
318
let toKey = getLanguageKeyFromValue(to, GTPTranslateLanguages);
319
320
let openai: OpenAI;
321
322
switch (provider) {
323
case 'openai': {
324
const apiKey = process.env.OPENAI_API_KEY;
325
if (!apiKey) warn('process.env.OPENAI_API_KEY is not defined');
326
openai = new OpenAI({ apiKey });
327
break;
328
}
329
case 'groq': {
330
const apiKey = process.env.GROQ_API_KEY;
331
if (!apiKey) warn('process.env.GROQ_API_KEY is not defined');
332
openai = new OpenAI({
333
baseURL: 'https://api.groq.com/openai/v1',
334
apiKey,
335
});
336
break;
337
}
338
case 'llama-cpp': {
339
const apiKey = process.env.LLAMA_API_KEY || 'not-needed';
340
openai = new OpenAI({
341
baseURL: 'http://localhost:8080/v1',
342
apiKey,
343
});
344
break;
345
}
346
default:
347
throw new Error(`Unsupported provider: ${provider}`);
348
}
349
350
try {
351
let conversationHistory: ChatCompletionRequestMessage[] = [
352
{
353
role: 'system',
354
content:
355
'You are a translation assistant. Translate any text given to you into the specified language. Do not return anything else.',
356
},
357
{
358
role: 'user',
359
content: `${fromKey} to ${toKey}: "${str}"`,
360
},
361
];
362
363
const response = await openai.chat.completions.create({
364
model: model,
365
messages: conversationHistory,
366
max_tokens: 1000,
367
});
368
369
let translation = response?.choices?.[0].message?.content?.trim() || '';
370
371
// remove first " if exist
372
translation =
373
translation[0] == '"' ? translation.substring(1) : translation;
374
375
// remove last " if exist
376
translation =
377
translation[translation.length - 1] == '"'
378
? translation.substring(0, translation.length - 1)
379
: translation;
380
381
return translation || 'Translation failed';
382
} catch (error) {
383
throw new Error(`Failed to translate text with GPT: ${error}`);
384
}
385
}
386
387