Fix quartes

Google translator, when translating direct speech, for some reason adds an additional quotation mark, which breaks the syntax
1.Before submitting text for translation, we replace all quotation marks with special markers (__OPEN_QUOTE__ and __CLOSE_QUOTE__).
This ensures that quotes are not changed or deleted during translation.
2.Similarly, we replace asterisks with markers (__OPEN_STAR__ and __CLOSE_STAR__).
3.After receiving the translated text, we replace all markers back to the corresponding characters.
This commit is contained in:
Himickoff 2024-07-13 19:13:08 +07:00
parent bf682be17a
commit 8e17117854
1 changed files with 21 additions and 3 deletions

View File

@ -64,7 +64,7 @@ router.post('/libre', jsonParser, async (request, response) => {
router.post('/google', jsonParser, async (request, response) => { router.post('/google', jsonParser, async (request, response) => {
try { try {
const { generateRequestUrl, normaliseResponse } = require('google-translate-api-browser'); const { generateRequestUrl, normaliseResponse } = require('google-translate-api-browser');
const text = request.body.text; let text = request.body.text;
const lang = request.body.lang; const lang = request.body.lang;
if (!text || !lang) { if (!text || !lang) {
@ -73,6 +73,20 @@ router.post('/google', jsonParser, async (request, response) => {
console.log('Input text: ' + text); console.log('Input text: ' + text);
// Заменяем кавычки на специальные маркеры перед переводом
const openQuote = '__OPEN_QUOTE__';
const closeQuote = '__CLOSE_QUOTE__';
text = text.replace(/"/g, (match, offset) => {
return offset % 2 === 0 ? openQuote : closeQuote;
});
// Заменяем звездочки на специальные маркеры
const openStar = '__OPEN_STAR__';
const closeStar = '__CLOSE_STAR__';
text = text.replace(/\*/g, (match, offset) => {
return offset % 2 === 0 ? openStar : closeStar;
});
const url = generateRequestUrl(text, { to: lang }); const url = generateRequestUrl(text, { to: lang });
https.get(url, (resp) => { https.get(url, (resp) => {
@ -87,8 +101,12 @@ router.post('/google', jsonParser, async (request, response) => {
const result = normaliseResponse(JSON.parse(data)); const result = normaliseResponse(JSON.parse(data));
console.log('Translated text: ' + result.text); console.log('Translated text: ' + result.text);
// Заменяем кавычки «» на "" // Восстанавливаем кавычки и звездочки после перевода
const fixedText = result.text.replace(/«/g, '"').replace(/»/g, '"'); let fixedText = result.text
.replace(new RegExp(openQuote, 'g'), '"')
.replace(new RegExp(closeQuote, 'g'), '"')
.replace(new RegExp(openStar, 'g'), '*')
.replace(new RegExp(closeStar, 'g'), '*');
return response.send(fixedText); return response.send(fixedText);
} catch (error) { } catch (error) {