attranslate
Version:
Semi-automated Text Translator for Websites and Apps
77 lines (76 loc) • 3.06 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.invokeTranslationService = void 0;
const matcher_definitions_1 = require("../matchers/matcher-definitions");
const service_definitions_1 = require("../services/service-definitions");
async function invokeTranslationService(serviceInputs, args) {
if (args.prompt && !["openai", "typechat"].includes(args.service)) {
console.warn(`Warning: The '--prompt' parameter is only supported by 'openai' and 'typechat' services. Your prompt will be ignored when using '${args.service}'.`);
}
/**
* Some translation services throw errors if they see empty strings.
* Therefore, we bypass empty strings without changing them.
*/
const rawInputs = [];
const results = new Map();
serviceInputs.forEach((value, key) => {
if (!value || !value.trim().length) {
results.set(key, value);
}
else {
rawInputs.push({
key,
value,
});
}
});
if (results.size) {
console.info(`Bypass ${results.size} strings because they are empty...`);
}
let translateResults = [];
if (rawInputs.length) {
translateResults = await runTranslationService(rawInputs, args);
}
translateResults.forEach((tResult) => {
results.set(tResult.key, tResult.translated);
});
return {
inputs: serviceInputs,
results,
};
}
exports.invokeTranslationService = invokeTranslationService;
async function runTranslationService(rawInputs, args) {
const matcher = (0, matcher_definitions_1.instantiateTMatcher)(args.matcher);
const replacers = new Map();
rawInputs.forEach((rawString) => {
const replacer = (0, matcher_definitions_1.replaceInterpolations)(rawString.value, matcher);
replacers.set(rawString.key, replacer);
});
const replacedInputs = rawInputs.map((rawString) => {
return {
key: rawString.key,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
value: replacers.get(rawString.key).clean,
};
});
const serviceArgs = {
strings: replacedInputs,
srcLng: args.srcLng,
targetLng: args.targetLng,
serviceConfig: args.serviceConfig,
prompt: args.prompt,
};
console.info(`Invoke '${args.service}' from '${args.srcLng}' to '${args.targetLng}' with ${serviceArgs.strings.length} inputs...`);
const translationService = await (0, service_definitions_1.instantiateTService)(args.service);
const rawResults = await translationService.translateStrings(serviceArgs);
return rawResults.map((rawResult) => {
const cleanResult = (0, matcher_definitions_1.reInsertInterpolations)(rawResult.translated,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
replacers.get(rawResult.key).replacements);
return {
key: rawResult.key,
translated: cleanResult,
};
});
}