deepl-mark/src/translate.ts

50 lines
1.3 KiB
TypeScript

import type { SourceLanguageCode, TargetLanguageCode } from 'deepl-node';
import { Translator } from 'deepl-node';
/**
* Translate an array of strings from sourceLang to targetLang using DeepL.
* Batches requests in groups of 10.
* Requires DEEPL_AUTH_KEY environment variable.
*/
export async function translateStrings(
strings: string[],
sourceLang: SourceLanguageCode,
targetLang: TargetLanguageCode
): Promise<string[]> {
if (strings.length === 0) return [];
const DEEPL_AUTH_KEY = process.env.DEEPL_AUTH_KEY;
if (!DEEPL_AUTH_KEY) throw new Error('DEEPL_AUTH_KEY environment variable must be set');
const deepl = new Translator(DEEPL_AUTH_KEY);
const translations: string[] = new Array(strings.length).fill('');
const queue: [index: number, string: string][] = [];
for (const [index, string] of strings.entries()) {
queue.push([index, string]);
if (index === strings.length - 1 || queue.length === 10) {
const indexes = queue.map(([i]) => i);
const batch = queue.map(([, s]) => s);
const results = await deepl.translateText(
batch,
sourceLang,
targetLang,
{
tagHandling: 'html',
splitSentences: 'nonewlines'
}
);
for (let j = 0; j < indexes.length; j++) {
translations[indexes[j]] = results[j].text;
}
queue.length = 0;
}
}
return translations;
}